text
stringlengths 3
1.05M
|
---|
(window.webpackJsonp=window.webpackJsonp||[]).push([[27],{142:function(e,n,t){"use strict";t.d(n,"a",(function(){return b})),t.d(n,"b",(function(){return p}));var a=t(0),r=t.n(a);function i(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function o(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);n&&(a=a.filter((function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable}))),t.push.apply(t,a)}return t}function s(e){for(var n=1;n<arguments.length;n++){var t=null!=arguments[n]?arguments[n]:{};n%2?o(Object(t),!0).forEach((function(n){i(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):o(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}))}return e}function c(e,n){if(null==e)return{};var t,a,r=function(e,n){if(null==e)return{};var t,a,r={},i=Object.keys(e);for(a=0;a<i.length;a++)t=i[a],n.indexOf(t)>=0||(r[t]=e[t]);return r}(e,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)t=i[a],n.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(r[t]=e[t])}return r}var l=r.a.createContext({}),u=function(e){var n=r.a.useContext(l),t=n;return e&&(t="function"==typeof e?e(n):s(s({},n),e)),t},b=function(e){var n=u(e.components);return r.a.createElement(l.Provider,{value:n},e.children)},m={inlineCode:"code",wrapper:function(e){var n=e.children;return r.a.createElement(r.a.Fragment,{},n)}},d=r.a.forwardRef((function(e,n){var t=e.components,a=e.mdxType,i=e.originalType,o=e.parentName,l=c(e,["components","mdxType","originalType","parentName"]),b=u(t),d=a,p=b["".concat(o,".").concat(d)]||b[d]||m[d]||i;return t?r.a.createElement(p,s(s({ref:n},l),{},{components:t})):r.a.createElement(p,s({ref:n},l))}));function p(e,n){var t=arguments,a=n&&n.mdxType;if("string"==typeof e||a){var i=t.length,o=new Array(i);o[0]=d;var s={};for(var c in n)hasOwnProperty.call(n,c)&&(s[c]=n[c]);s.originalType=e,s.mdxType="string"==typeof e?e:a,o[1]=s;for(var l=2;l<i;l++)o[l]=t[l];return r.a.createElement.apply(null,o)}return r.a.createElement.apply(null,t)}d.displayName="MDXCreateElement"},143:function(e,n,t){"use strict";var a=t(0),r=t(19);n.a=function(){var e=Object(a.useContext)(r.a);if(null===e)throw new Error("Docusaurus context not provided");return e}},144:function(e,n,t){"use strict";t.d(n,"b",(function(){return i})),t.d(n,"a",(function(){return o}));var a=t(143),r=t(145);function i(){var e=Object(a.a)().siteConfig,n=(e=void 0===e?{}:e).baseUrl,t=void 0===n?"/":n,i=e.url;return{withBaseUrl:function(e,n){return function(e,n,t,a){var i=void 0===a?{}:a,o=i.forcePrependBaseUrl,s=void 0!==o&&o,c=i.absolute,l=void 0!==c&&c;if(!t)return t;if(t.startsWith("#"))return t;if(Object(r.b)(t))return t;if(s)return n+t;var u=t.startsWith(n)?t:n+t.replace(/^\//,"");return l?e+u:u}(i,t,e,n)}}}function o(e,n){return void 0===n&&(n={}),(0,i().withBaseUrl)(e,n)}},145:function(e,n,t){"use strict";function a(e){return!0===/^(\w*:|\/\/)/.test(e)}function r(e){return void 0!==e&&!a(e)}t.d(n,"b",(function(){return a})),t.d(n,"a",(function(){return r}))},146:function(e,n,t){"use strict";function a(e){var n,t,r="";if("string"==typeof e||"number"==typeof e)r+=e;else if("object"==typeof e)if(Array.isArray(e))for(n=0;n<e.length;n++)e[n]&&(t=a(e[n]))&&(r&&(r+=" "),r+=t);else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}n.a=function(){for(var e,n,t=0,r="";t<arguments.length;)(e=arguments[t++])&&(n=a(e))&&(r&&(r+=" "),r+=n);return r}},147:function(e,n,t){"use strict";var a=t(0),r=Object(a.createContext)(void 0);n.a=r},148:function(e,n,t){"use strict";var a=t(0),r=t(147);n.a=function(){var e=Object(a.useContext)(r.a);if(null==e)throw new Error("`useUserPreferencesContext` is used outside of `Layout` Component.");return e}},149:function(e,n,t){"use strict";var a=t(0),r=t.n(a),i=t(148),o=t(146),s=t(47),c=t.n(s),l=37,u=39;n.a=function(e){var n=e.block,t=e.children,s=e.defaultValue,b=e.values,m=e.groupId,d=Object(i.a)(),p=d.tabGroupChoices,y=d.setTabGroupChoices,O=Object(a.useState)(s),j=O[0],g=O[1],v=Object(a.useState)(!1),h=v[0],N=v[1];if(null!=m){var f=p[m];null!=f&&f!==j&&b.some((function(e){return e.value===f}))&&g(f)}var C=function(e){g(e),null!=m&&y(m,e)},I=[],w=function(e){e.metaKey||e.altKey||e.ctrlKey||N(!0)},P=function(){N(!1)};return Object(a.useEffect)((function(){window.addEventListener("keydown",w),window.addEventListener("mousedown",P)}),[]),r.a.createElement("div",null,r.a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:Object(o.a)("tabs",{"tabs--block":n})},b.map((function(e){var n=e.value,t=e.label;return r.a.createElement("li",{role:"tab",tabIndex:0,"aria-selected":j===n,className:Object(o.a)("tabs__item",c.a.tabItem,{"tabs__item--active":j===n}),style:h?{}:{outline:"none"},key:n,ref:function(e){return I.push(e)},onKeyDown:function(e){!function(e,n,t){switch(t.keyCode){case u:!function(e,n){var t=e.indexOf(n)+1;e[t]?e[t].focus():e[0].focus()}(e,n);break;case l:!function(e,n){var t=e.indexOf(n)-1;e[t]?e[t].focus():e[e.length-1].focus()}(e,n)}}(I,e.target,e),w(e)},onFocus:function(){return C(n)},onClick:function(){C(n),N(!1)},onPointerDown:function(){return N(!1)}},t)}))),r.a.createElement("div",{role:"tabpanel",className:"margin-vert--md"},a.Children.toArray(t).filter((function(e){return e.props.value===j}))[0]))}},150:function(e,n,t){"use strict";var a=t(0),r=t.n(a);n.a=function(e){return r.a.createElement("div",null,e.children)}},83:function(e,n,t){"use strict";t.r(n),t.d(n,"frontMatter",(function(){return c})),t.d(n,"metadata",(function(){return l})),t.d(n,"rightToc",(function(){return u})),t.d(n,"default",(function(){return m}));var a=t(2),r=t(6),i=(t(0),t(142)),o=(t(144),t(149)),s=t(150),c={id:"dbcontext-hight-query",title:"9.11 \u9ad8\u7ea7\u67e5\u8be2\u64cd\u4f5c",sidebar_label:"9.11 \u9ad8\u7ea7\u67e5\u8be2\u64cd\u4f5c"},l={unversionedId:"dbcontext-hight-query",id:"dbcontext-hight-query",isDocsHomePage:!1,title:"9.11 \u9ad8\u7ea7\u67e5\u8be2\u64cd\u4f5c",description:"9.11.1 \u5173\u8054\u6570\u636e\u6a21\u578b",source:"@site/docs\\dbcontext-high-query.mdx",slug:"/dbcontext-hight-query",permalink:"/docs/dbcontext-hight-query",editUrl:"https://gitee.com/monksoul/Fur/tree/main/handbook/docs/dbcontext-high-query.mdx",version:"current",sidebar_label:"9.11 \u9ad8\u7ea7\u67e5\u8be2\u64cd\u4f5c",sidebar:"docs",previous:{title:"9.10 \u67e5\u8be2\u64cd\u4f5c",permalink:"/docs/dbcontext-query"},next:{title:"9.12 \u89c6\u56fe\u64cd\u4f5c",permalink:"/docs/dbcontext-view"}},u=[{value:"9.11.1 \u5173\u8054\u6570\u636e\u6a21\u578b",id:"9111-\u5173\u8054\u6570\u636e\u6a21\u578b",children:[]},{value:"9.11.2 \u4e00\u5bf9\u4e00\u67e5\u8be2",id:"9112-\u4e00\u5bf9\u4e00\u67e5\u8be2",children:[]},{value:"9.11.3 \u4e00\u5bf9\u591a\u67e5\u8be2",id:"9113-\u4e00\u5bf9\u591a\u67e5\u8be2",children:[]},{value:"9.11.4 \u591a\u5bf9\u591a\u67e5\u8be2",id:"9114-\u591a\u5bf9\u591a\u67e5\u8be2",children:[]},{value:"9.11.5 \u8054\u8868\u67e5\u8be2",id:"9115-\u8054\u8868\u67e5\u8be2",children:[{value:"9.11.5.1 \u5185\u8fde\u63a5 <code>Inner Join</code>",id:"91151-\u5185\u8fde\u63a5-inner-join",children:[]},{value:"9.11.5.2 \u5de6\u8fde\u63a5 <code>Left Join</code>",id:"91152-\u5de6\u8fde\u63a5-left-join",children:[]},{value:"9.11.5.2 \u53f3\u8fde\u63a5 <code>Right Join</code>",id:"91152-\u53f3\u8fde\u63a5-right-join",children:[]}]},{value:"9.11.6 \u5206\u7ec4\u67e5\u8be2",id:"9116-\u5206\u7ec4\u67e5\u8be2",children:[]},{value:"9.11.7 \u5408\u5e76\u7ed3\u679c\u96c6",id:"9117-\u5408\u5e76\u7ed3\u679c\u96c6",children:[]},{value:"9.11.8 \u67e5\u8be2\u6392\u5e8f",id:"9118-\u67e5\u8be2\u6392\u5e8f",children:[{value:"9.11.8.1 \u6b63\u5e8f",id:"91181-\u6b63\u5e8f",children:[]},{value:"9.11.8.2 \u5012\u5e8f",id:"91182-\u5012\u5e8f",children:[]},{value:"9.11.8.3 \u6df7\u5408\u5012\u5e8f",id:"91183-\u6df7\u5408\u5012\u5e8f",children:[]}]},{value:"9.11.9 \u9012\u5f52\u67e5\u8be2",id:"9119-\u9012\u5f52\u67e5\u8be2",children:[]},{value:"9.11.10 \u52a8\u6001 <code>Sql</code> \u67e5\u8be2",id:"91110-\u52a8\u6001-sql-\u67e5\u8be2",children:[{value:"9.11.10.1 \u52a8\u6001 <code>Sql</code>",id:"911101-\u52a8\u6001-sql",children:[]},{value:"9.11.10.2 \u52a8\u6001 <code>Lambda</code>",id:"911102-\u52a8\u6001-lambda",children:[]}]},{value:"9.11.11 \u6027\u80fd\u4f18\u5316",id:"91111-\u6027\u80fd\u4f18\u5316",children:[]},{value:"9.11.12 \u5206\u8868\u67e5\u8be2\u5c0f\u4f8b\u5b50",id:"91112-\u5206\u8868\u67e5\u8be2\u5c0f\u4f8b\u5b50",children:[]},{value:"9.11.12 \u53cd\u9988\u4e0e\u5efa\u8bae",id:"91112-\u53cd\u9988\u4e0e\u5efa\u8bae",children:[]}],b={rightToc:u};function m(e){var n=e.components,t=Object(r.a)(e,["components"]);return Object(i.b)("wrapper",Object(a.a)({},b,t,{components:n,mdxType:"MDXLayout"}),Object(i.b)("h2",{id:"9111-\u5173\u8054\u6570\u636e\u6a21\u578b"},"9.11.1 \u5173\u8054\u6570\u636e\u6a21\u578b"),Object(i.b)(o.a,{defaultValue:"person",values:[{label:"Person",value:"person"},{label:"PersonDetail",value:"person-detail"},{label:"Children",value:"children"},{label:"Post",value:"post"}],mdxType:"Tabs"},Object(i.b)(s.a,{value:"person",mdxType:"TabItem"},Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs",metastring:"{38,43,48}","{38,43,48}":!0}),"using Fur.DatabaseAccessor;\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace Fur.Core\n{\n public class Person : Entity\n {\n /// <summary>\n /// \u6784\u9020\u51fd\u6570\n /// </summary>\n public Person()\n {\n CreatedTime = DateTime.Now;\n IsDeleted = false;\n }\n\n /// <summary>\n /// \u59d3\u540d\n /// </summary>\n [MaxLength(32)]\n public string Name { get; set; }\n\n /// <summary>\n /// \u5e74\u9f84\n /// </summary>\n public int Age { get; set; }\n\n /// <summary>\n /// \u4f4f\u5740\n /// </summary>\n public string Address { get; set; }\n\n /// <summary>\n /// \u4ece\u8868\n /// </summary>\n public PersonDetail PersonDetail { get; set; }\n\n /// <summary>\n /// \u4e00\u5bf9\u591a\n /// </summary>\n public ICollection<Children> Childrens { get; set; }\n\n /// <summary>\n /// \u591a\u5bf9\u591a\n /// </summary>\n public ICollection<Post> Posts { get; set; }\n }\n}\n"))),Object(i.b)(s.a,{value:"person-detail",mdxType:"TabItem"},Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs",metastring:"{25}","{25}":!0}),"using Fur.DatabaseAccessor;\n\nnamespace Fur.Core\n{\n public class PersonDetail : EntityBase\n {\n /// <summary>\n /// \u7535\u8bdd\u53f7\u7801\n /// </summary>\n public string PhoneNumber { get; set; }\n\n /// <summary>\n /// QQ \u53f7\u7801\n /// </summary>\n public string QQ { get; set; }\n\n /// <summary>\n /// \u5916\u952e\n /// </summary>\n public int PersonId { get; set; }\n\n /// <summary>\n /// \u4e3b\u8868\n /// </summary>\n public Person Person { get; set; }\n }\n}\n"))),Object(i.b)(s.a,{value:"children",mdxType:"TabItem"},Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs",metastring:"{35}","{35}":!0}),"using Fur.DatabaseAccessor;\nusing System;\n\nnamespace Fur.Core\n{\n public class Children : Entity\n {\n /// <summary>\n /// \u6784\u9020\u51fd\u6570\n /// </summary>\n public Children()\n {\n CreatedTime = DateTime.Now;\n IsDeleted = false;\n }\n\n /// <summary>\n /// \u540d\u79f0\n /// </summary>\n public string Name { get; set; }\n\n /// <summary>\n /// \u6027\u522b\n /// </summary>\n public Gender Gender { get; set; }\n\n /// <summary>\n /// \u5916\u952e\n /// </summary>\n public int PersonId { get; set; }\n\n /// <summary>\n /// \u4e3b\u8868\n /// </summary>\n public Person Person { get; set; }\n }\n}\n"))),Object(i.b)(s.a,{value:"post",mdxType:"TabItem"},Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs",metastring:"{26}","{26}":!0}),"using Fur.DatabaseAccessor;\nusing System;\nusing System.Collections.Generic;\n\nnamespace Fur.Core\n{\n public class Post : Entity\n {\n /// <summary>\n /// \u6784\u9020\u51fd\u6570\n /// </summary>\n public Post()\n {\n CreatedTime = DateTime.Now;\n IsDeleted = false;\n }\n\n /// <summary>\n /// \u540d\u79f0\n /// </summary>\n public string Name { get; set; }\n\n /// <summary>\n /// Person \u96c6\u5408\n /// </summary>\n public ICollection<Person> Persons { get; set; }\n }\n}\n")))),Object(i.b)("h2",{id:"9112-\u4e00\u5bf9\u4e00\u67e5\u8be2"},"9.11.2 \u4e00\u5bf9\u4e00\u67e5\u8be2"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"// \u793a\u4f8b\u4e00\nvar person = repository.Include(u => u.Detail);\n\n// \u793a\u4f8b\u4e8c\nvar person = repository.Include(u => u.Detail)\n .Include(u => u.Post);\n\n// \u793a\u4f8b\u4e09\nvar person = repository.Include(u => u.Detail)\n .ThenInclude(d => d.Review)\n .Include(u => u.Post);\n\n// \u793a\u4f8b\u56db\nvar person = repository.Include(u => u.Detail.Where(d => d.Id > 10).OrderBy(d => d.Name))\n .ThenInclude(d => d.Review)\n .Include(u => u.Post);\n\n// \u793a\u4f8b\u4e94\nvar person = repository.IncludeIf(!string.IsNullOrEmpty(keyword), u => u.Detail);\n\n// \u793a\u4f8b\u516d\nvar person = repository.IncludeIf(!string.IsNullOrEmpty(keyword), u => u.Detail)\n .IncludeIf(age > 18), u => u.Detail.Where(d => d.Id > 10).OrderBy(d => d.Name))\n .ThenInclude(d => d.Review)\n .Include(u => u.Post);\n")),Object(i.b)("h2",{id:"9113-\u4e00\u5bf9\u591a\u67e5\u8be2"},"9.11.3 \u4e00\u5bf9\u591a\u67e5\u8be2"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"// \u793a\u4f8b\u4e00\nvar person = repository.Include(u => u.Childrens);\n\n// \u53c2\u8003 \u4e00\u5bf9\u4e00 \u4f8b\u5b50\n")),Object(i.b)("div",{className:"admonition admonition-important alert alert--info"},Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-heading"}),Object(i.b)("h5",{parentName:"div"},Object(i.b)("span",Object(a.a)({parentName:"h5"},{className:"admonition-icon"}),Object(i.b)("svg",Object(a.a)({parentName:"span"},{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"16",viewBox:"0 0 14 16"}),Object(i.b)("path",Object(a.a)({parentName:"svg"},{fillRule:"evenodd",d:"M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"})))),"\u7279\u522b\u8bf4\u660e")),Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-content"}),Object(i.b)("p",{parentName:"div"},Object(i.b)("inlineCode",{parentName:"p"},"\u4e00\u5bf9\u4e00")," \u548c ",Object(i.b)("inlineCode",{parentName:"p"},"\u4e00\u5bf9\u591a")," \u67e5\u8be2\u65b9\u6cd5\u4e00\u6837\uff0c\u552f\u4e00\u7684\u533a\u522b\u662f\uff1a",Object(i.b)("inlineCode",{parentName:"p"},"\u4e00\u5bf9\u591a")," \u91c7\u7528 ",Object(i.b)("inlineCode",{parentName:"p"},"ICollection<TEntity>")," \u5b9a\u4e49\u5c5e\u6027\u3002"))),Object(i.b)("h2",{id:"9114-\u591a\u5bf9\u591a\u67e5\u8be2"},"9.11.4 \u591a\u5bf9\u591a\u67e5\u8be2"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"// \u793a\u4f8b\u4e00\nvar person = repository.Include(u => u.Posts);\n\n// \u53c2\u8003 \u4e00\u5bf9\u4e00 \u4f8b\u5b50\n")),Object(i.b)("div",{className:"admonition admonition-important alert alert--info"},Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-heading"}),Object(i.b)("h5",{parentName:"div"},Object(i.b)("span",Object(a.a)({parentName:"h5"},{className:"admonition-icon"}),Object(i.b)("svg",Object(a.a)({parentName:"span"},{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"16",viewBox:"0 0 14 16"}),Object(i.b)("path",Object(a.a)({parentName:"svg"},{fillRule:"evenodd",d:"M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"})))),"\u7279\u522b\u8bf4\u660e")),Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-content"}),Object(i.b)("p",{parentName:"div"},Object(i.b)("inlineCode",{parentName:"p"},"\u4e00\u5bf9\u4e00")," \u548c ",Object(i.b)("inlineCode",{parentName:"p"},"\u591a\u5bf9\u591a")," \u67e5\u8be2\u65b9\u6cd5\u4e00\u6837\uff0c\u552f\u4e00\u7684\u533a\u522b\u662f\uff1a",Object(i.b)("inlineCode",{parentName:"p"},"\u591a\u5bf9\u591a")," \u91c7\u7528 ",Object(i.b)("inlineCode",{parentName:"p"},"ICollection<TEntity>")," \u5b9a\u4e49\u5c5e\u6027\u3002"))),Object(i.b)("h2",{id:"9115-\u8054\u8868\u67e5\u8be2"},"9.11.5 \u8054\u8868\u67e5\u8be2"),Object(i.b)("h3",{id:"91151-\u5185\u8fde\u63a5-inner-join"},"9.11.5.1 \u5185\u8fde\u63a5 ",Object(i.b)("inlineCode",{parentName:"h3"},"Inner Join")),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"var query = from p in _personRepository.AsQueryable()\n join d in _personDetailRepository.AsQueryable() on p.Id equals d.PersonId\n select new PersonDto\n {\n PhoneNumber = p.PersonDetail.PhoneNumber,\n Address = p.Address,\n Age = p.Age,\n Name = p.Name,\n Id = p.Id,\n QQ = p.PersonDetail.QQ\n };\n")),Object(i.b)("h3",{id:"91152-\u5de6\u8fde\u63a5-left-join"},"9.11.5.2 \u5de6\u8fde\u63a5 ",Object(i.b)("inlineCode",{parentName:"h3"},"Left Join")),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs",metastring:"{2,3}","{2,3}":!0}),"var query = from p in _personRepository.AsQueryable()\n join d in _personDetailRepository.AsQueryable() on p.Id equals d.PersonId into results\n from d in results.DefaultIfEmpty()\n select new PersonDto\n {\n PhoneNumber = p.PersonDetail.PhoneNumber,\n Address = p.Address,\n Age = p.Age,\n Name = p.Name,\n Id = p.Id,\n QQ = p.PersonDetail.QQ\n };\n")),Object(i.b)("div",{className:"admonition admonition-note alert alert--secondary"},Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-heading"}),Object(i.b)("h5",{parentName:"div"},Object(i.b)("span",Object(a.a)({parentName:"h5"},{className:"admonition-icon"}),Object(i.b)("svg",Object(a.a)({parentName:"span"},{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"16",viewBox:"0 0 14 16"}),Object(i.b)("path",Object(a.a)({parentName:"svg"},{fillRule:"evenodd",d:"M6.3 5.69a.942.942 0 0 1-.28-.7c0-.28.09-.52.28-.7.19-.18.42-.28.7-.28.28 0 .52.09.7.28.18.19.28.42.28.7 0 .28-.09.52-.28.7a1 1 0 0 1-.7.3c-.28 0-.52-.11-.7-.3zM8 7.99c-.02-.25-.11-.48-.31-.69-.2-.19-.42-.3-.69-.31H6c-.27.02-.48.13-.69.31-.2.2-.3.44-.31.69h1v3c.02.27.11.5.31.69.2.2.42.31.69.31h1c.27 0 .48-.11.69-.31.2-.19.3-.42.31-.69H8V7.98v.01zM7 2.3c-3.14 0-5.7 2.54-5.7 5.68 0 3.14 2.56 5.7 5.7 5.7s5.7-2.55 5.7-5.7c0-3.15-2.56-5.69-5.7-5.69v.01zM7 .98c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.12-7-7 3.14-7 7-7z"})))),"\u5c0f\u63d0\u793a")),Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-content"}),Object(i.b)("p",{parentName:"div"},Object(i.b)("strong",{parentName:"p"},Object(i.b)("inlineCode",{parentName:"strong"},"Left Join"))," \u548c ",Object(i.b)("strong",{parentName:"p"},Object(i.b)("inlineCode",{parentName:"strong"},"Inner Join"))," \u4e0d\u540c\u7684\u662f\uff0c",Object(i.b)("strong",{parentName:"p"},Object(i.b)("inlineCode",{parentName:"strong"},"Left Join"))," \u4f1a\u5148\u5c06\u7ed3\u679c ",Object(i.b)("strong",{parentName:"p"},Object(i.b)("inlineCode",{parentName:"strong"},"into"))," \u5230\u65b0\u7684\u7ed3\u679c\u96c6\u7136\u540e\u518d\u67e5\u8be2\uff0c\u5e76\u8c03\u7528 ",Object(i.b)("strong",{parentName:"p"},Object(i.b)("inlineCode",{parentName:"strong"},"DefaultIfEmpty()"))," \u65b9\u6cd5\u3002"))),Object(i.b)("h3",{id:"91152-\u53f3\u8fde\u63a5-right-join"},"9.11.5.2 \u53f3\u8fde\u63a5 ",Object(i.b)("inlineCode",{parentName:"h3"},"Right Join")),Object(i.b)("p",null,Object(i.b)("inlineCode",{parentName:"p"},"Right Join")," \u53ea\u9700\u8981\u5c06 ",Object(i.b)("inlineCode",{parentName:"p"},"Left Join")," \u4e3b\u4ece\u8868\u4f4d\u7f6e\u66f4\u6362\u5373\u53ef\u3002"),Object(i.b)("h2",{id:"9116-\u5206\u7ec4\u67e5\u8be2"},"9.11.6 \u5206\u7ec4\u67e5\u8be2"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"// \u793a\u4f8b\u4e00\nvar query = repository.AsQueryable().GroupBy(x => new { x.Column1, x.Column2 });\n\n// \u793a\u4f8b\u4e8c\nvar query = from student in repository.AsQueryable()\n group student by repository2.AsQueryable() into dateGroup\n select new ResultData()\n {\n Key = dateGroup.Key,\n Value = dateGroup.Count()\n };\n\n// \u793a\u4f8b\u4e09\nvar query = from a in repository.AsQueryable()\n join b in repository2.AsQueryable() on a.Id equals b.Aid\n join c in repository3.AsQueryable() on c.id equals b.Bid\n group emp by new { emp.Age, emp.Sex } into g\n select new {\n Peo = g.Key,\n Count = g.Count()\n };\n")),Object(i.b)("h2",{id:"9117-\u5408\u5e76\u7ed3\u679c\u96c6"},"9.11.7 \u5408\u5e76\u7ed3\u679c\u96c6"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"var query = repository.AsQueryable(u => u.Id > 10)\n .Union(\n repository2.AsQueryable(u => u.Id <= 10)\n );\n")),Object(i.b)("h2",{id:"9118-\u67e5\u8be2\u6392\u5e8f"},"9.11.8 \u67e5\u8be2\u6392\u5e8f"),Object(i.b)("h3",{id:"91181-\u6b63\u5e8f"},"9.11.8.1 \u6b63\u5e8f"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"// \u793a\u4f8b\u4e00\nvar query = repository.AsQueryable()\n .OrderBy(u => u.Id);\n\n// \u793a\u4f8b\u4e8c\nvar query =repository.AsQueryable()\n .OrderBy(u => u.Id)\n .ThenBy(u => u.Name);\n")),Object(i.b)("h3",{id:"91182-\u5012\u5e8f"},"9.11.8.2 \u5012\u5e8f"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"// \u793a\u4f8b\u4e00\nvar query = repository.AsQueryable()\n .OrderByDescending(u => u.Id);\n\n// \u793a\u4f8b\u4e8c\nvar query =repository.AsQueryable()\n .OrderByDescending(u => u.Id)\n .ThenByDescending(u => u.Name);\n")),Object(i.b)("h3",{id:"91183-\u6df7\u5408\u5012\u5e8f"},"9.11.8.3 \u6df7\u5408\u5012\u5e8f"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"// \u793a\u4f8b\u4e00\nvar query = repository.AsQueryable()\n .OrderBy(u => u.Id)\n .OrderByDescending(u => u.Name)\n .ThenBy(u => u.Age);\n")),Object(i.b)("h2",{id:"9119-\u9012\u5f52\u67e5\u8be2"},"9.11.9 \u9012\u5f52\u67e5\u8be2"),Object(i.b)(o.a,{defaultValue:"city",values:[{label:"City",value:"city"},{label:"CityDto",value:"citydto"}],mdxType:"Tabs"},Object(i.b)(s.a,{value:"city",mdxType:"TabItem"},Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs",metastring:"{12,36,41,49-55}","{12,36,41,49-55}":!0}),'using Fur.DatabaseAccessor;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore.Metadata.Builders;\nusing System;\nusing System.Collections.Generic;\n\nnamespace Fur.Core\n{\n /// <summary>\n /// \u57ce\u5e02\n /// </summary>\n public class City : Entity, IEntityTypeBuilder<City>, IEntitySeedData<City>\n {\n /// <summary>\n /// \u6784\u9020\u51fd\u6570\n /// </summary>\n public City()\n {\n CreatedTime = DateTime.Now;\n IsDeleted = false;\n }\n\n /// <summary>\n /// \u540d\u79f0\n /// </summary>\n public string Name { get; set; }\n\n /// <summary>\n /// \u4e0a\u7ea7Id\n /// </summary>\n public int? ParentId { get; set; }\n\n /// <summary>\n /// \u4e0a\u7ea7\n /// </summary>\n public virtual City Parent { get; set; }\n\n /// <summary>\n /// \u5b50\u96c6\n /// </summary>\n public virtual ICollection<City> Childrens { get; set; }\n\n /// <summary>\n /// \u914d\u7f6e\u5b9e\u4f53\u5173\u7cfb\n /// </summary>\n /// <param name="entityBuilder"></param>\n /// <param name="dbContext"></param>\n /// <param name="dbContextLocator"></param>\n public void Configure(EntityTypeBuilder<City> entityBuilder, DbContext dbContext, Type dbContextLocator)\n {\n entityBuilder\n .HasMany(x => x.Childrens)\n .WithOne(x => x.Parent)\n .HasForeignKey(x => x.ParentId)\n .OnDelete(DeleteBehavior.ClientSetNull); // \u5fc5\u987b\u8bbe\u7f6e\u8fd9\u4e00\u884c\n }\n\n /// <summary>\n /// \u79cd\u5b50\u6570\u636e\n /// </summary>\n /// <param name="dbContext"></param>\n /// <param name="dbContextLocator"></param>\n /// <returns></returns>\n public IEnumerable<City> HasData(DbContext dbContext, Type dbContextLocator)\n {\n return new List<City>\n {\n new City { Id=1,CreatedTime =DateTime.Parse("2020-08-20 15:30:20"),IsDeleted=false,Name="\u4e2d\u56fd" },\n new City { Id=2,CreatedTime =DateTime.Parse("2020-08-20 15:30:20"),IsDeleted=false,Name="\u5e7f\u4e1c\u7701",ParentId=1 },\n new City { Id=3,CreatedTime =DateTime.Parse("2020-08-20 15:30:20"),IsDeleted=false,Name="\u4e2d\u5c71\u5e02",ParentId=2 },\n new City { Id=4,CreatedTime =DateTime.Parse("2020-08-20 15:30:20"),IsDeleted=false,Name="\u73e0\u6d77\u5e02",ParentId=2 },\n new City { Id=5,CreatedTime =DateTime.Parse("2020-08-20 15:30:20"),IsDeleted=false,Name="\u6d59\u6c5f\u7701",ParentId=1 },\n };\n }\n }\n}\n'))),Object(i.b)(s.a,{value:"citydto",mdxType:"TabItem"},Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"using System.Collections.Generic;\n\nnamespace Fur.Application.Persons\n{\n public class CityDto\n {\n /// <summary>\n /// \u9010\u6e10\n /// </summary>\n public int Id { get; set; }\n\n /// <summary>\n /// \u540d\u79f0\n /// </summary>\n public string Name { get; set; }\n\n /// <summary>\n /// \u5b50\u96c6\n /// </summary>\n public ICollection<CityDto> Childrens { get; set; }\n }\n}\n")))),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"var cities = await repository.AsQueryable()\n .Include(u => u.Childrens)\n .Where(u => u.Id == 1)\n .ToListAsync();\n\nvar dtos = cities.Adapt<List<CityDto>>();\n")),Object(i.b)("h2",{id:"91110-\u52a8\u6001-sql-\u67e5\u8be2"},"9.11.10 \u52a8\u6001 ",Object(i.b)("inlineCode",{parentName:"h2"},"Sql")," \u67e5\u8be2"),Object(i.b)("p",null,Object(i.b)("inlineCode",{parentName:"p"},"Fur")," \u9ed8\u8ba4\u4e0d\u652f\u6301 \u52a8\u6001 ",Object(i.b)("inlineCode",{parentName:"p"},"Sql")," \u67e5\u8be2\u529f\u80fd\uff0c\u4e0d\u8fc7\u53ef\u4ee5\u901a\u8fc7\u7b2c\u4e09\u65b9\u5b9e\u73b0\uff1a"),Object(i.b)("p",null,"\u5728 ",Object(i.b)("inlineCode",{parentName:"p"},"Fur")," \u9879\u76ee\u5c42\u5b89\u88c5 ",Object(i.b)("inlineCode",{parentName:"p"},"System.Linq.Dynamic.Core")," \u5305 ",Object(i.b)("a",Object(a.a)({parentName:"p"},{href:"https://github.com/zzzprojects/System.Linq.Dynamic.Core"}),"https://github.com/zzzprojects/System.Linq.Dynamic.Core")),Object(i.b)("h3",{id:"911101-\u52a8\u6001-sql"},"9.11.10.1 \u52a8\u6001 ",Object(i.b)("inlineCode",{parentName:"h3"},"Sql")),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),'// \u793a\u4f8b\u4e00\nvar query = repository.AsQueryable()\n .Where("City == @0 and Orders.Count >= @1", "China", 10)\n .OrderBy("CompanyName")\n .Select("new(CompanyName as Name, Phone)");\n\n// \u793a\u4f8b\u4e8c\nvar list = repository.AsQueryable()\n .Where("Name.Contains(@0)","Fur")\n .ToList();\n\n// \u793a\u4f8b\u4e09\uff0c\u652f\u6301 ? \u8bed\u6cd5\nvar customers = repository.AsQueryable()\n .Include(c => c.Location)\n .Where(c => c.Location?.Name == "test") // \u6ce8\u610f Location?.Name\n .ToList();\n')),Object(i.b)("h3",{id:"911102-\u52a8\u6001-lambda"},"9.11.10.2 \u52a8\u6001 ",Object(i.b)("inlineCode",{parentName:"h3"},"Lambda")),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),'// \u793a\u4f8b\u4e00\nvar x = Expression.Parameter(typeof(int), "x");\nvar y = Expression.Parameter(typeof(int), "y");\nvar e = DynamicExpressionParser\n .ParseLambda(new ParameterExpression[] { x, y }, null, "(x + y) * 2");\n\n// \u793a\u4f8b\u4e8c\nvar e = DynamicExpressionParser.ParseLambda(\n typeof(Customer), typeof(bool),\n "City = @0 and Orders.Count >= @1",\n "London", 10);\n')),Object(i.b)("h2",{id:"91111-\u6027\u80fd\u4f18\u5316"},"9.11.11 \u6027\u80fd\u4f18\u5316"),Object(i.b)("p",null,"\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c",Object(i.b)("inlineCode",{parentName:"p"},"EF Core")," \u4f1a\u8ddf\u8e2a\u6240\u6709\u5b9e\u4f53\uff0c\u4e5f\u5c31\u662f\u4efb\u4f55\u6570\u636e\u6539\u53d8\u90fd\u4f1a\u5f15\u8d77\u6570\u636e\u68c0\u67e5\uff0c\u6240\u4ee5\u5982\u679c\u53ea\u505a\u67e5\u8be2\u64cd\u4f5c\uff0c\u5efa\u8bae\u5173\u95ed\u5b9e\u4f53\u8ddf\u8e2a\u529f\u80fd\u3002"),Object(i.b)("p",null,Object(i.b)("inlineCode",{parentName:"p"},"Fur")," \u6846\u67b6\u63d0\u4f9b\u4e86\u4ee5\u4e0b\u9ad8\u6027\u80fd\u5b9e\u4f53\u96c6\u5408\uff1a"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"DetachedEntities"),"\uff1a\u8131\u8f68/\u4e0d\u8ffd\u8e2a\u5b9e\u4f53"),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"AsQueryable()"),"\uff1a\u4e0d\u8ffd\u8e2a\u5b9e\u4f53"),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"Entities.AsNoTracking()"),"\uff1a\u624b\u52a8\u5173\u95ed\u5b9e\u4f53\u8ffd\u8e2a")),Object(i.b)("p",null,"\u5728 ",Object(i.b)("inlineCode",{parentName:"p"},"EF Core")," \u4e2d\uff0c\u590d\u6742\u67e5\u8be2\u603b\u662f\u4f1a\u751f\u6210\u4e00\u4e2a ",Object(i.b)("inlineCode",{parentName:"p"},"sql"),"\uff0c\u4e5f\u5c31\u662f ",Object(i.b)("inlineCode",{parentName:"p"},"AsSingleQuery()"),"\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u8bbe\u7f6e\u4e3a ",Object(i.b)("inlineCode",{parentName:"p"},"AsSplitQuery()")," \u5207\u5272\u6210\u591a\u4e2a\u67e5\u8be2\u3002"),Object(i.b)("h2",{id:"91112-\u5206\u8868\u67e5\u8be2\u5c0f\u4f8b\u5b50"},"9.11.12 \u5206\u8868\u67e5\u8be2\u5c0f\u4f8b\u5b50"),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),'using Fur.DatabaseAccessor;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore.Metadata.Builders;\nusing System;\nusing System.Collections.Generic;\n\nnamespace Fur.Core\n{\n public class Person : Entity, IEntityTypeBuilder<Person>\n {\n public string Name { get; set; }\n\n /// <summary>\n /// \u914d\u7f6e\u5b9e\u4f53\u5173\u7cfb\n /// </summary>\n /// <param name="entityBuilder"></param>\n /// <param name="dbContext"></param>\n /// <param name="dbContextLocator"></param>\n public void Configure(EntityTypeBuilder<City> entityBuilder, DbContext dbContext, Type dbContextLocator)\n {\n entityBuilder.ToSqlQuery(\n @"select * from dbo.person.2020-09-19\n union all\n select * from dbo.person.2020-09-20");\n }\n }\n}\n')),Object(i.b)("pre",null,Object(i.b)("code",Object(a.a)({parentName:"pre"},{className:"language-cs"}),"var posts = repository.Where(u => u.Id > 10).ToList();\n")),Object(i.b)("h2",{id:"91112-\u53cd\u9988\u4e0e\u5efa\u8bae"},"9.11.12 \u53cd\u9988\u4e0e\u5efa\u8bae"),Object(i.b)("div",{className:"admonition admonition-note alert alert--secondary"},Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-heading"}),Object(i.b)("h5",{parentName:"div"},Object(i.b)("span",Object(a.a)({parentName:"h5"},{className:"admonition-icon"}),Object(i.b)("svg",Object(a.a)({parentName:"span"},{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"16",viewBox:"0 0 14 16"}),Object(i.b)("path",Object(a.a)({parentName:"svg"},{fillRule:"evenodd",d:"M6.3 5.69a.942.942 0 0 1-.28-.7c0-.28.09-.52.28-.7.19-.18.42-.28.7-.28.28 0 .52.09.7.28.18.19.28.42.28.7 0 .28-.09.52-.28.7a1 1 0 0 1-.7.3c-.28 0-.52-.11-.7-.3zM8 7.99c-.02-.25-.11-.48-.31-.69-.2-.19-.42-.3-.69-.31H6c-.27.02-.48.13-.69.31-.2.2-.3.44-.31.69h1v3c.02.27.11.5.31.69.2.2.42.31.69.31h1c.27 0 .48-.11.69-.31.2-.19.3-.42.31-.69H8V7.98v.01zM7 2.3c-3.14 0-5.7 2.54-5.7 5.68 0 3.14 2.56 5.7 5.7 5.7s5.7-2.55 5.7-5.7c0-3.15-2.56-5.69-5.7-5.69v.01zM7 .98c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.12-7-7 3.14-7 7-7z"})))),"\u4e0e\u6211\u4eec\u4ea4\u6d41")),Object(i.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-content"}),Object(i.b)("p",{parentName:"div"},"\u7ed9 Fur \u63d0 ",Object(i.b)("a",Object(a.a)({parentName:"p"},{href:"https://gitee.com/monksoul/Fur/issues/new?issue"}),"Issue"),"\u3002"))))}m.isMDXComponent=!0}}]); |
import React from 'react';
const NotFoundPage = () => {
return (
<div>
<h3>Page not found</h3>
</div>
);
};
export default NotFoundPage;
|
import {
PURCHASE_CATEGORY_ALCOHOL,
PURCHASE_CATEGORY_COMBINED_PASSENGER_TRANSPORT,
PURCHASE_CATEGORY_ELECTRICITY,
PURCHASE_CATEGORY_FINANCIAL_SERVICES,
PURCHASE_CATEGORY_FOOD,
PURCHASE_CATEGORY_FOOD_SERVING_SERVICES,
PURCHASE_CATEGORY_HEALTHCARE_DOCTOR,
PURCHASE_CATEGORY_INFORMATION_COMMUNICATION,
PURCHASE_CATEGORY_INSURANCE,
PURCHASE_CATEGORY_MAINTENANCE_DWELLING,
PURCHASE_CATEGORY_MEDICINES_AND_HEALTH_PRODUCTS,
PURCHASE_CATEGORY_MISC_DWELLING,
PURCHASE_CATEGORY_MISC_SERVICES_PERSONAL_TRANSPORT,
PURCHASE_CATEGORY_NON_DURABLE_HOUSEHOLD_GOODS,
PURCHASE_CATEGORY_OTHER_PERSONAL_EFFECTS,
PURCHASE_CATEGORY_OTHER_SERVICES,
PURCHASE_CATEGORY_OTHER_TRANSPORT_SERVICES,
PURCHASE_CATEGORY_READY_FOOD,
PURCHASE_CATEGORY_RECREATIONAL_DURABLES,
PURCHASE_CATEGORY_RECREATIONAL_SERVICES,
PURCHASE_CATEGORY_RENTAL,
PURCHASE_CATEGORY_SOCIAL_PROTECTION,
PURCHASE_CATEGORY_STORE_BOOKS,
PURCHASE_CATEGORY_STORE_CLOTHING,
PURCHASE_CATEGORY_STORE_FOOD,
PURCHASE_CATEGORY_STORE_FURNISHING,
PURCHASE_CATEGORY_STORE_GARDEN_AND_PET,
PURCHASE_CATEGORY_STORE_HARDWARE,
PURCHASE_CATEGORY_STORE_PERSONAL_CARE,
PURCHASE_CATEGORY_TRANSPORT_AIR,
PURCHASE_CATEGORY_TRANSPORT_ROAD,
PURCHASE_CATEGORY_TRANSPORTATION_AUTOMOTIVE_MAINTENANCE_AND_REPAIR,
PURCHASE_CATEGORY_TRANSPORTATION_FUEL,
} from '../../../definitions';
import { getActivityTypeForPurchaseCategory } from '../../utils/activityTypeForPurchaseCategory';
// Match NAG categories to our own categories
const categoryToCategory = {
'ATM & Checks': null,
'Advisors & Services': PURCHASE_CATEGORY_OTHER_SERVICES,
'Alimony & Child Support': PURCHASE_CATEGORY_SOCIAL_PROTECTION,
'Auto & Transport': PURCHASE_CATEGORY_OTHER_SERVICES,
'Auto Insurance & Assistance': PURCHASE_CATEGORY_INSURANCE,
'Auto Loan etc.': null,
Baby: PURCHASE_CATEGORY_OTHER_PERSONAL_EFFECTS,
'Bank Fees': PURCHASE_CATEGORY_FINANCIAL_SERVICES,
'Basic Expenses': PURCHASE_CATEGORY_FOOD,
Betting: PURCHASE_CATEGORY_OTHER_SERVICES,
'Building Insurance': PURCHASE_CATEGORY_INSURANCE,
'Car Rental': PURCHASE_CATEGORY_TRANSPORT_ROAD,
'Child Benefits': null,
'Child Care & Tuition': null,
'Child Savings': null,
'Cinema, Concerts & Entertainment': PURCHASE_CATEGORY_RECREATIONAL_SERVICES,
'Clothing & Accessories': PURCHASE_CATEGORY_STORE_CLOTHING,
'Consumer Loan': null,
'Contents Insurance': PURCHASE_CATEGORY_INSURANCE,
'Debt & Interest': null,
Education: null,
'Electronics & Computer': PURCHASE_CATEGORY_INFORMATION_COMMUNICATION,
Exclude: null,
'Fast Food & Takeaway': PURCHASE_CATEGORY_FOOD_SERVING_SERVICES,
Fines: null,
'Flights & Hotels': PURCHASE_CATEGORY_TRANSPORT_AIR,
'Food & Drinks': PURCHASE_CATEGORY_STORE_FOOD,
Fuel: PURCHASE_CATEGORY_TRANSPORTATION_FUEL,
'Furniture & Interior': PURCHASE_CATEGORY_STORE_FURNISHING,
'Games & Toys': PURCHASE_CATEGORY_RECREATIONAL_DURABLES,
'Garage & Auto Parts': PURCHASE_CATEGORY_TRANSPORTATION_AUTOMOTIVE_MAINTENANCE_AND_REPAIR,
'Garden & Plants': PURCHASE_CATEGORY_STORE_GARDEN_AND_PET,
'Gifts & Charity': null,
'Glasses & Contacts': PURCHASE_CATEGORY_MEDICINES_AND_HEALTH_PRODUCTS,
'Hairdresser & Personal Care': PURCHASE_CATEGORY_STORE_PERSONAL_CARE,
'Health Insurance': PURCHASE_CATEGORY_INSURANCE,
Hide: null,
'Hobby & Sports Equipment': PURCHASE_CATEGORY_RECREATIONAL_DURABLES,
'Holiday Pay': null,
Home: PURCHASE_CATEGORY_NON_DURABLE_HOUSEHOLD_GOODS,
'Home Security': PURCHASE_CATEGORY_MAINTENANCE_DWELLING,
'Homeowners Association': PURCHASE_CATEGORY_MISC_DWELLING,
Household: PURCHASE_CATEGORY_NON_DURABLE_HOUSEHOLD_GOODS,
'Housekeeping & Gardening': PURCHASE_CATEGORY_STORE_HARDWARE,
'Housing Benefit': null,
Income: null,
Interest: null,
'Interest Income': null,
'Late Fees': PURCHASE_CATEGORY_FINANCIAL_SERVICES,
Leisure: PURCHASE_CATEGORY_RECREATIONAL_SERVICES,
'Life & Accident Insurance': PURCHASE_CATEGORY_INSURANCE,
'Meal Plan': PURCHASE_CATEGORY_STORE_FOOD,
'Medical Specialists': PURCHASE_CATEGORY_HEALTHCARE_DOCTOR,
Memberships: PURCHASE_CATEGORY_OTHER_SERVICES,
'Mini-markets & Delicacies': PURCHASE_CATEGORY_READY_FOOD,
'Mortgage/Rent': PURCHASE_CATEGORY_RENTAL,
'Movies, Music & Books': PURCHASE_CATEGORY_STORE_BOOKS,
'Online Services & Software': PURCHASE_CATEGORY_INFORMATION_COMMUNICATION,
Other: null,
'Other Housing Expenses': PURCHASE_CATEGORY_NON_DURABLE_HOUSEHOLD_GOODS,
'Other Income': null,
'Other Private Consumption': null,
'Other Savings': null,
'Other Transport': PURCHASE_CATEGORY_COMBINED_PASSENGER_TRANSPORT,
'Overpaid Tax': null,
Parking: PURCHASE_CATEGORY_MISC_SERVICES_PERSONAL_TRANSPORT,
'Pension & Savings': null,
'Pension Payout': null,
'Pension Savings': null,
Pets: PURCHASE_CATEGORY_STORE_GARDEN_AND_PET,
Pharmacy: PURCHASE_CATEGORY_MEDICINES_AND_HEALTH_PRODUCTS,
'Phone & Internet': PURCHASE_CATEGORY_INFORMATION_COMMUNICATION,
'Private Loan (Friends & Family)': null,
'Property Tax': null,
'Public Transport': PURCHASE_CATEGORY_COMBINED_PASSENGER_TRANSPORT,
'Public fee': null,
'Remodeling & Repair': PURCHASE_CATEGORY_STORE_HARDWARE,
'Road Tax & Green Tax': null,
Salary: null,
'Shared Expense': null,
'Sports & Leisure': PURCHASE_CATEGORY_RECREATIONAL_SERVICES,
'Stock Trading': null,
'Student Grant': null,
'Student Loan': null,
Supermarket: PURCHASE_CATEGORY_STORE_FOOD,
'TV license & Cable': PURCHASE_CATEGORY_INFORMATION_COMMUNICATION,
Taxi: PURCHASE_CATEGORY_TRANSPORT_ROAD,
'Tobacco & Alcohol': PURCHASE_CATEGORY_ALCOHOL,
Transfer: null,
Travel: PURCHASE_CATEGORY_OTHER_TRANSPORT_SERVICES,
'Travel Insurance': PURCHASE_CATEGORY_INSURANCE,
Tuition: PURCHASE_CATEGORY_OTHER_SERVICES,
'Unemployment Benefits': null,
'Union & Unemployment Insurance': PURCHASE_CATEGORY_INSURANCE,
Unknown: null,
'Unpayed Tax': null,
Utilities: PURCHASE_CATEGORY_ELECTRICITY,
'Vacation Activities': PURCHASE_CATEGORY_RECREATIONAL_SERVICES,
'Vacation Home & Camping': PURCHASE_CATEGORY_RECREATIONAL_SERVICES,
'Vacation Home Expenses': PURCHASE_CATEGORY_NON_DURABLE_HOUSEHOLD_GOODS,
'Yield & Returns': null,
};
export const NAG_CATEGORY = Object.entries(categoryToCategory).reduce(
(accumulator, [id, purchaseCategory]) => {
accumulator[id] = purchaseCategory
? getActivityTypeForPurchaseCategory(purchaseCategory)
: null;
return accumulator;
},
{}
);
// Deliberately want activities that match the following
// To be created with the ignored=true value
export const CATEGORIES_TO_IGNORE = [
'Child Benefits',
'Holiday Pay',
'Housing Benefit',
'Overpaid Tax',
'Pension & Savings',
'Pension Payout',
'Pension Savings',
'Property Tax',
'Public fee',
'Salary',
'Road Tax & Green Tax',
'Salary',
'Unemployment Benefits',
'Unpayed Tax',
];
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Products(models.Model):
SUB_CHOICES = [(100, 'HealthPlus'),
(200, 'CasaBella')]
upc = models.CharField(max_length=200)
alu = models.CharField(max_length=200, null=True, blank=True)
subsidiary = models.CharField(choices=SUB_CHOICES, max_length=20)
description = models.CharField(max_length=250)
attributes = models.CharField(max_length=50, null=True, blank=True)
size = models.CharField(max_length=50, null=True, blank=True)
cost = models.FloatField()
price = models.FloatField()
is_active = models.BooleanField(default=True)
class Meta:
verbose_name = ("Products")
verbose_name_plural = ("Products")
def __str__(self):
return self.description
def toJson(self):
return json.dumps(self, default=lambda o: o.__dict__)
# def get_absolute_url(self):
# return reverse("Products_detail", kwargs={"pk": self.pk})
class Region(models.Model):
region = models.CharField(max_length=200)
Manager = models.ForeignKey(
User, on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self):
return self.region
class Stores(models.Model):
SUB_CHOICES = [('100', 'HealthPlus'),
('200', 'CasaBella')]
name = models.CharField(max_length=200)
subsidiary = models.CharField(choices=SUB_CHOICES, max_length=20)
store_code = models.CharField(max_length=5)
email = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
region = models.ForeignKey(
"Region", on_delete=models.SET_NULL, null=True, blank=True)
is_active = models.BooleanField(default=True)
class Meta:
verbose_name = ("stores")
verbose_name_plural = ("stores")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("stores_detail", kwargs={"pk": self.pk})
class Lostsales(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(
'Products', on_delete=models.CASCADE, related_name='product')
quantity = models.IntegerField(default=1)
store = models.ForeignKey("Stores", null=True, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now=True)
# TODO: Define fields here
class Meta:
"""Meta definition for Lostsales."""
verbose_name = 'Lostsales'
verbose_name_plural = 'Lostsales'
def __str__(self):
return self.product.description
class Staff(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
branch = models.ForeignKey(
"stores", on_delete=models.SET_NULL, null=True, blank=True)
# TODO: Define fields here
class Meta:
"""Meta definition for Staff."""
verbose_name = 'Staff'
verbose_name_plural = 'Staff'
def __str__(self):
return self.user.username
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v6/enums/attribution_model.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/ads/googleads/v6/enums/attribution_model.proto',
package='google.ads.googleads.v6.enums',
syntax='proto3',
serialized_options=b'\n!com.google.ads.googleads.v6.enumsB\025AttributionModelProtoP\001ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v6/enums;enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V6.Enums\312\002\035Google\\Ads\\GoogleAds\\V6\\Enums\352\002!Google::Ads::GoogleAds::V6::Enums',
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n5google/ads/googleads/v6/enums/attribution_model.proto\x12\x1dgoogle.ads.googleads.v6.enums\x1a\x1cgoogle/api/annotations.proto\"\xc6\x02\n\x14\x41ttributionModelEnum\"\xad\x02\n\x10\x41ttributionModel\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\x0c\n\x08\x45XTERNAL\x10\x64\x12\x19\n\x15GOOGLE_ADS_LAST_CLICK\x10\x65\x12)\n%GOOGLE_SEARCH_ATTRIBUTION_FIRST_CLICK\x10\x66\x12$\n GOOGLE_SEARCH_ATTRIBUTION_LINEAR\x10g\x12(\n$GOOGLE_SEARCH_ATTRIBUTION_TIME_DECAY\x10h\x12,\n(GOOGLE_SEARCH_ATTRIBUTION_POSITION_BASED\x10i\x12)\n%GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN\x10jB\xea\x01\n!com.google.ads.googleads.v6.enumsB\x15\x41ttributionModelProtoP\x01ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v6/enums;enums\xa2\x02\x03GAA\xaa\x02\x1dGoogle.Ads.GoogleAds.V6.Enums\xca\x02\x1dGoogle\\Ads\\GoogleAds\\V6\\Enums\xea\x02!Google::Ads::GoogleAds::V6::Enumsb\x06proto3'
,
dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,])
_ATTRIBUTIONMODELENUM_ATTRIBUTIONMODEL = _descriptor.EnumDescriptor(
name='AttributionModel',
full_name='google.ads.googleads.v6.enums.AttributionModelEnum.AttributionModel',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='UNSPECIFIED', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='EXTERNAL', index=2, number=100,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='GOOGLE_ADS_LAST_CLICK', index=3, number=101,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='GOOGLE_SEARCH_ATTRIBUTION_FIRST_CLICK', index=4, number=102,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='GOOGLE_SEARCH_ATTRIBUTION_LINEAR', index=5, number=103,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='GOOGLE_SEARCH_ATTRIBUTION_TIME_DECAY', index=6, number=104,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='GOOGLE_SEARCH_ATTRIBUTION_POSITION_BASED', index=7, number=105,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN', index=8, number=106,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=144,
serialized_end=445,
)
_sym_db.RegisterEnumDescriptor(_ATTRIBUTIONMODELENUM_ATTRIBUTIONMODEL)
_ATTRIBUTIONMODELENUM = _descriptor.Descriptor(
name='AttributionModelEnum',
full_name='google.ads.googleads.v6.enums.AttributionModelEnum',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_ATTRIBUTIONMODELENUM_ATTRIBUTIONMODEL,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=119,
serialized_end=445,
)
_ATTRIBUTIONMODELENUM_ATTRIBUTIONMODEL.containing_type = _ATTRIBUTIONMODELENUM
DESCRIPTOR.message_types_by_name['AttributionModelEnum'] = _ATTRIBUTIONMODELENUM
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AttributionModelEnum = _reflection.GeneratedProtocolMessageType('AttributionModelEnum', (_message.Message,), {
'DESCRIPTOR' : _ATTRIBUTIONMODELENUM,
'__module__' : 'google.ads.googleads.v6.enums.attribution_model_pb2'
# @@protoc_insertion_point(class_scope:google.ads.googleads.v6.enums.AttributionModelEnum)
})
_sym_db.RegisterMessage(AttributionModelEnum)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Atriina and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestInterview(unittest.TestCase):
pass
|
module.exports = function(grunt) {
var fs = require('fs');
grunt.initConfig({
mochaTest: {
test: {
src: ["spec/*.spec.js"]
}
},
http: {
scalers: {
options: {
url: "https://api.clever-cloud.com/v2/products/instances",
gzip: true,
agent: new (require("https").Agent)({ keepAlive: true }),
callback: function(error, response, body){
if(error){
grunt.log.error(error);
} else{
var content = "module.exports=" + JSON.stringify(JSON.parse(body));
fs.writeFileSync("./spec/application.instance-types.js", content);
}
}
}
}
}
});
grunt.loadNpmTasks('grunt-http');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('test', ['http', 'mochaTest']);
};
|
import json
import io
def util_load_json(path):
with io.open(path, mode='r', encoding='utf-8') as f:
return json.loads(f.read())
def test_authenticate_user(requests_mock):
from FireMonSecurityManager import Client, authenticate_command
mock_response = util_load_json('test_data/get_authentication.json')
requests_mock.post('https://example.test.com/securitymanager/api/authentication/login', json=mock_response)
client = Client(
base_url='https://example.test.com',
verify=False,
proxy=False,
username="test",
password="test")
response = authenticate_command(client)
assert response is not None
assert response.raw_response['authorized'] is True
def test_create_pp_ticket_command(requests_mock):
from FireMonSecurityManager import Client, create_pp_ticket_command
mock_response = util_load_json('test_data/get_authentication.json')
requests_mock.post('https://example.test.com/securitymanager/api/authentication/login', json=mock_response)
mock_response = util_load_json('test_data/get_workflows.json')
requests_mock.get('https://example.test.com/policyplanner/api/domain/1/workflow/version/latest/all',
json=mock_response)
mock_response = util_load_json('test_data/get_pp_ticket.json')
requests_mock.post('https://example.test.com/policyplanner/api/domain/1/workflow/3/packet',
json=mock_response)
client = Client(
base_url='https://example.test.com',
verify=False,
proxy=False,
username="test",
password="test")
args = {'domain_id': 1,
'workflow_name': 'Access Req WF',
'requirement': [{"action": "ACCEPT",
"destinations": "2.2.2.2",
"services": "http",
"sources": "1.1.1.1"}],
'priority': 'Low',
'due_date': '2021-08-26T03:50:17-04:00'}
response = create_pp_ticket_command(client, args=args)
assert response is not None
assert response.outputs_prefix == 'FireMonSecurityManager.CreatePPTicket'
def test_pca_new_command(requests_mock):
from FireMonSecurityManager import Client, pca_command
mock_response = util_load_json('test_data/get_authentication.json')
requests_mock.post('https://example.test.com/securitymanager/api/authentication/login', json=mock_response)
mock_response = util_load_json('test_data/get_rule_rec.json')
requests_mock.post('https://example.test.com/orchestration/api/domain/1/change/rulerec', json=mock_response)
mock_response = util_load_json('test_data/get_pca.json')
requests_mock.post('https://example.test.com/orchestration/api/domain/1/change/device/9/pca', json=mock_response)
client = Client(
base_url='https://example.test.com',
verify=False,
proxy=False,
username="test",
password="test")
args = {'sources': '10.1.1.1',
'destinations': '1.1.1.1',
'services': 'tcp/8080',
'action': 'ACCEPT',
'domain_id': 1,
'device_group_id': 1}
response = pca_command(client, args=args)
assert response is not None
assert response.outputs_prefix == 'FireMonSecurityManager.PCA'
|
import React, { Component } from 'react';
class MapShow extends Component {
render() {
return 'MapShow';
}
}
export default MapShow;
|
"""
请求参数模型
"""
from pydantic import BaseModel, Field
from .model import UserBase
class Token(BaseModel):
access_token: str = Field(..., description='Token值')
token_type: str = Field(..., description='Token类型')
# 创建账号需要验证的条件
class UserCreate(UserBase):
confirm: str = Field(..., description='确认密码')
class Config:
"""
schema_extra中设置参数的例子,在API文档中可以看到
"""
schema_extra = {
'example': {
'username': 'guest',
'nickname': '访客',
'email': '[email protected]',
'mobile': '10086',
'password': '123456',
'confirm': '123456',
'avatar': 'https://img2.woyaogexing.com/2021/05/03/dfcfaaffa8ed4e1a819eba8c10b856d4!400x400.jpeg'
}
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# elements_gui.py
# Copyright (c) 2005-2013, Christoph Gohlke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holders nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Periodic Table of Elements - A user interface for elements.py.
:Author: `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_
:Version: 2013.03.18
Requirements
------------
* `CPython 2.7 <http://www.python.org>`_
* `wxPython 2.8 <http://www.wxpython.org>`_
* `Elements.py 2013.03.18 <http://www.lfd.uci.edu/~gohlke/>`_
"""
from __future__ import division, print_function
import sys
import math
import io
import webbrowser
import wxversion
wxversion.ensureMinimal('2.8')
import wx
from wx.lib import fancytext, buttons, rcsizer
from phaseshifts.elements import ELEMENTS, SERIES
class MainApp(wx.App):
"""Main application."""
name = "Periodic Table of Elements"
version = "2012.04.05"
website = "http://www.lfd.uci.edu/~gohlke/"
copyright = ("Christoph Gohlke\n"
"Laboratory for Fluorescence Dynamics\n"
"University of California, Irvine")
icon = "elements"
def OnInit(self):
_ = wx.LogNull()
wx.InitAllImageHandlers()
mainframe = MainFrame(None, -1)
self.SetTopWindow(mainframe)
if wx.Platform != "__WXMAC__":
mainframe.Centre()
mainframe.ApplyLayout(False)
mainframe.Show()
return 1
class MainFrame(wx.Frame):
"""Main application window."""
def __init__(self, *args, **kwds):
kwds["style"] = (wx.DEFAULT_DIALOG_STYLE|wx.MINIMIZE_BOX|
wx.TAB_TRAVERSAL)
wx.Frame.__init__(self, *args, **kwds)
self.selected = -1
self.SetTitle(MainApp.name)
icon = wx.EmptyIcon()
icon.CopyFromBitmap(wx.Bitmap(MainApp.icon + '.png',
wx.BITMAP_TYPE_ANY))
self.SetIcon(icon)
self.SetBackgroundColour(wx.SystemSettings_GetColour(
wx.SYS_COLOUR_3DFACE))
# create menu
self.menu = wx.MenuBar()
self.SetMenuBar(self.menu)
menu = wx.Menu()
menu.Append(wx.ID_EXIT, "Exit", "Exit the application", wx.ITEM_NORMAL)
self.menu.Append(menu, "File")
menu = wx.Menu()
menu.Append(wx.ID_COPY,
"Copy\tCtrl+C", "Copy selected element to the clipboard",
wx.ITEM_NORMAL)
self.menu.Append(menu, "Edit")
menu = wx.Menu()
menu.Append(wx.ID_VIEW_DETAILS, "Details", "Show or hide details",
wx.ITEM_CHECK)
self.menu.Append(menu, "View")
menu = wx.Menu()
menu.Append(wx.ID_ABOUT, "About...",
"Display information about the program", wx.ITEM_NORMAL)
self.menu.Append(menu, "Help")
# create panels and controls
self.notebook = wx.Notebook(self, -1, style=0)
self.description = DecriptionPanel(self.notebook, -1)
self.details = DetailsPanel(self.notebook, -1)
self.table = PeriodicPanel(self, -1)
self.disclose = DisclosureCtrl(self.table, -1, '')
self.table.AddCtrl(self.disclose)
self.notebook.AddPage(self.description, "Description")
self.notebook.AddPage(self.details, "Properties")
# event bindings
self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
self.Bind(wx.EVT_MENU, self.OnCopy, id=wx.ID_COPY)
self.Bind(wx.EVT_MENU, self.OnDetails, id=wx.ID_VIEW_DETAILS)
self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
self.Bind(EVT_ELE_CHANGED, self.OnSelect, self.table)
self.Bind(EVT_ELE_CHANGED, self.OnSelect, self.details)
self.Bind(wx.EVT_BUTTON, self.OnDetails, self.disclose)
# create sizers
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.table, 1, (wx.LEFT|wx.TOP|wx.RIGHT|wx.EXPAND|
wx.ALIGN_CENTER_HORIZONTAL| wx.EXPAND|wx.ADJUST_MINSIZE), BORDER-5)
self.sizer.Add((BORDER, BORDER))
self.sizer.Add(self.notebook, 0, (wx.LEFT|wx.RIGHT|wx.BOTTOM|
wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|
wx.ADJUST_MINSIZE), BORDER)
self.notebook.SetSelection(1)
self.SetAutoLayout(True)
self.SetSizerAndFit(self.sizer, True)
self.sizer.SetSizeHints(self)
self.ApplyLayout(True)
self.SetSelection(0)
def ApplyLayout(self, show=False):
self.show_info = show
self.sizer.Show(2, show, True)
self.SetAutoLayout(True)
self.SetSizerAndFit(self.sizer, True)
self.sizer.SetSizeHints(self)
self.Layout()
self.menu.Check(wx.ID_VIEW_DETAILS, show)
self.disclose.SetToggle(self.show_info)
def OnDetails(self, evt):
self.ApplyLayout(not self.show_info)
def OnEraseBackground(self, event):
pass
def OnCopy(self, evt):
dobj = wx.TextDataObject()
dobj.SetText(repr(ELEMENTS[self.selected + 1]))
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(dobj)
wx.TheClipboard.Close()
def OnAbout(self, evt):
info = wx.AboutDialogInfo()
info.Name = MainApp.name
info.Version = MainApp.version
info.Copyright = MainApp.copyright
info.WebSite = MainApp.website
wx.AboutBox(info)
def OnWebsite(self, evt):
webbrowser.open(MainApp.website)
def OnWikipedia(self, evt):
webbrowser.open("http://en.wikipedia.org/wiki/%s" % (
ELEMENTS[self.selected].name), 1)
def OnWebElements(self, evt):
webbrowser.open("http://www.webelements.com/%s/" % (
ELEMENTS[self.selected].name.lower()))
def OnSelect(self, evt):
self.SetSelection(evt.GetSelection())
def SetSelection(self, select):
"""Set active element."""
if self.selected != select:
self.selected = select
self.description.SetSelection(select)
self.table.SetSelection(select)
self.details.SetSelection(select)
def OnExit(self, evt):
self.Close()
if __name__ == "__main__":
sys.exit(0)
else:
return self.selected
class PeriodicPanel(wx.Panel):
"""Periodic table of elements panel."""
layout = """
. 1 . . . . . . . . . . . . . . . . 18 .
1 H 2 . . . . . . . . . . 13 14 15 16 17 He .
2 Li Be . . . . . . . . . . B C N O F Ne .
3 Na Mg 3 4 5 6 7 8 9 10 11 12 Al Si P S Cl Ar .
4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr .
5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe .
6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn .
7 Fr Ra ** Rf Db Sg Bh Hs Mt . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . * La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu .
. . . ** Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr .
"""
def __init__(self, *args, **kwds):
kwds["style"] = wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
rows = len(self.layout.splitlines()) - 2
cols = len(self.layout.splitlines()[1].split())
self.sizer = wx.FlexGridSizer(rows, cols, 0, 0)
self.buttons = list(range(0, len(ELEMENTS)))
self.selected = -1
self.info = ElementPanel(self, -1, pos=(0, 0))
# create element buttons
buttonsize = math.ceil(float(self.info.GetSize()[0] + 4) / 9.0)
if buttonsize < 30:
buttonsize = 30
for row in self.layout.splitlines()[1:-1]:
for col in row.split():
if col == '.':
self.sizer.Add((SPACER, SPACER))
elif col[0] in '123456789*':
static = wx.StaticText(self, -1, col,
style=wx.ALIGN_CENTER|wx.ALIGN_BOTTOM)
self.sizer.Add(static, 0,
(wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|
wx.ALIGN_CENTER_VERTICAL|wx.FIXED_MINSIZE), SPACER//2)
else:
ele = ELEMENTS[col]
button = ElementButton(self, ele.number+100, ele.symbol,
size=(buttonsize, buttonsize))
self.buttons[ele.number - 1] = button
button.SetBezelWidth(1)
button.SetToolTipString(ele.name)
col = COLORS[ele.series]
button.SetButtonColour(wx.Colour(col[0], col[1], col[2]))
self.sizer.Add(button, 0, (wx.LEFT|wx.BOTTOM|
wx.FIXED_MINSIZE|wx.ALIGN_CENTER_HORIZONTAL|
wx.ALIGN_CENTER_VERTICAL), 0)
self.Bind(wx.EVT_BUTTON, self.OnSelect, button)
self.SetAutoLayout(True)
self.SetSizer(self.sizer)
self.sizer.SetSizeHints(self)
self.sizer.Fit(self)
# position element info panel
cw = self.sizer.GetColWidths()
rh = self.sizer.GetRowHeights()
self.info.Move((sum(cw[:3])+cw[3]//2, (rh[0]-SPACER)//2-1))
# legend of chemical series
self.legendpos = (sum(cw[:13]), (rh[0]-SPACER)//2-1)
self.legendsize = (sum(cw[13:17]) + cw[17]//2, -1)
self.legend = wx.StaticText(self, -1, " Alkaline earth metals ",
style=wx.ALIGN_CENTER, pos=self.legendpos, size=self.legendsize)
self.legend.SetToolTipString("Chemical series")
# blinking element button
self.highlight = False
self.timer = wx.Timer(self)
self.timer.Start(750)
self.Bind(wx.EVT_TIMER, self.OnTimer)
def AddCtrl(self, ctrl, pos=200):
self.sizer.Remove(pos)
self.sizer.Insert(pos, ctrl, 0, (wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|
wx.ALIGN_BOTTOM|wx.FIXED_MINSIZE), 0)
self.Layout()
def OnTimer(self, evt):
button = self.buttons[self.selected]
button.SetToggle(button.up)
def OnSelect(self, evt):
self.GetParent().SetSelection(evt.GetId() - 101)
def SetSelection(self, select):
"""Set active element."""
if self.selected == select:
return
# reset old selection
self.buttons[self.selected].SetToggle(False)
# highlight new selection
self.selected = select
self.buttons[select].SetToggle(True)
ele = ELEMENTS[select + 1]
col = COLORS[ele.series]
self.legend.SetBackgroundColour(wx.Colour(col[0], col[1], col[2]))
self.legend.SetLabel(SERIES[ele.series])
self.legend.Move(self.legendpos)
self.legend.SetSize(self.legendsize)
self.info.SetSelection(select)
class ElementPanel(wx.Panel):
"""Element information panel."""
def __init__(self, *args, **kwds):
kwds["style"] = wx.NO_BORDER | wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
self.selected = -1
# create controls
self.number = wx.StaticText(self, -1, "808",
style=wx.ALIGN_RIGHT)
self.position = wx.StaticText(self, -1, "6, 88, 9",
style=wx.ALIGN_LEFT)
self.symbol = wx.StaticText(self, -1, "Mm",
style=wx.ALIGN_CENTER_HORIZONTAL)
self.name = wx.StaticText(self, -1, "Praseodymium ",
style=wx.ALIGN_CENTER_HORIZONTAL)
self.mass = wx.StaticText(self, -1, "123.4567890 ",
style=wx.ALIGN_CENTER_HORIZONTAL)
self.massnumber = wx.StaticText(self, -1, "123 A ",
style=wx.ALIGN_RIGHT)
self.protons = wx.StaticText(self, -1, "123 P ",
style=wx.ALIGN_RIGHT)
self.neutrons = wx.StaticText(self, -1, "123 N ",
style=wx.ALIGN_RIGHT)
self.electrons = wx.StaticText(self, -1, "123 e ",
style=wx.ALIGN_RIGHT)
self.eleshell = wx.StaticText(self, -1, "2, 8, 18, 32, 32, 15, 2",
style=wx.ALIGN_LEFT)
self.eleconfig = StaticFancyText(self, -1,
"[Xe] 4f<sup>14</sup> 5d<sup>10</sup>"
" 6s<sup>2</sup> 6p<sup>6</sup> ",
style=wx.ALIGN_LEFT)
self.oxistates = wx.StaticText(self, -1, "1*, 2, 3, 4, 5, 6, -7 ")
self.atmrad = wx.StaticText(self, -1, "1.234 A ",
style=wx.ALIGN_RIGHT)
self.ionpot = wx.StaticText(self, -1, "123.4567890 eV ")
self.eleneg = wx.StaticText(self, -1, "123.45678 ")
# set control properties
font = self.GetFont()
font.SetWeight(wx.FONTWEIGHT_BOLD)
self.number.SetFont(font)
self.name.SetFont(font)
font.SetPointSize(font.GetPointSize() * 1.9)
self.symbol.SetFont(font)
self.number.SetToolTipString("Atomic number")
self.position.SetToolTipString("Group, Period, Block")
self.symbol.SetToolTipString("Symbol")
self.name.SetToolTipString("Name")
self.mass.SetToolTipString("Relative atomic mass")
self.eleshell.SetToolTipString("Electrons per shell")
self.massnumber.SetToolTipString("Mass number (most abundant isotope)")
self.protons.SetToolTipString("Protons")
self.neutrons.SetToolTipString("Neutrons (most abundant isotope)")
self.electrons.SetToolTipString("Electrons")
self.eleconfig.SetToolTipString("Electron configuration")
self.oxistates.SetToolTipString("Oxidation states")
self.atmrad.SetToolTipString("Atomic radius")
self.ionpot.SetToolTipString("Ionization potentials")
self.eleneg.SetToolTipString("Electronegativity")
# layout
sizer = rcsizer.RowColSizer()
sizer.col_w = SPACER
sizer.row_h = SPACER
sizer.Add(self.number, row=0, col=0,
flag=wx.ALIGN_CENTER_HORIZONTAL|wx.FIXED_MINSIZE)
sizer.Add(self.position, row=0, col=1,
flag=wx.ALIGN_LEFT|wx.FIXED_MINSIZE)
sizer.Add(self.symbol, row=1, col=0, rowspan=2, colspan=2,
flag=(wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|
wx.FIXED_MINSIZE))
sizer.Add(self.name, row=3, col=0, colspan=2,
flag=wx.ALIGN_CENTER_HORIZONTAL|wx.FIXED_MINSIZE)
sizer.Add(self.mass, row=4, col=0, colspan=2,
flag=wx.ALIGN_CENTER_HORIZONTAL|wx.FIXED_MINSIZE)
sizer.Add(self.massnumber, row=0, col=2,
flag=wx.ALIGN_RIGHT|wx.FIXED_MINSIZE)
sizer.Add(self.protons, row=1, col=2,
flag=wx.ALIGN_RIGHT|wx.FIXED_MINSIZE)
sizer.Add(self.neutrons, row=2, col=2,
flag=wx.ALIGN_RIGHT|wx.FIXED_MINSIZE)
sizer.Add(self.electrons, row=3, col=2,
flag=wx.ALIGN_RIGHT|wx.FIXED_MINSIZE)
sizer.Add(self.atmrad, row=4, col=2,
flag=wx.ALIGN_RIGHT|wx.FIXED_MINSIZE)
sizer.Add(self.eleconfig, row=0, col=4, flag=wx.ADJUST_MINSIZE)
sizer.Add(self.eleshell, row=1, col=4, flag=wx.ADJUST_MINSIZE)
sizer.Add(self.oxistates, row=2, col=4, flag=wx.ADJUST_MINSIZE)
sizer.Add(self.ionpot, row=3, col=4, flag=wx.ADJUST_MINSIZE)
sizer.Add(self.eleneg, row=4, col=4, flag=wx.ADJUST_MINSIZE)
self.SetAutoLayout(True)
self.SetSizer(sizer)
sizer.Fit(self)
sizer.SetSizeHints(self)
self.Layout()
def SetSelection(self, select):
"""Set active element."""
if self.selected == select:
return
self.Freeze()
self.selected = select
ele = ELEMENTS[select + 1]
self.number.SetLabel("%i" % ele.number)
self.position.SetLabel("%i, %i, %s" % (
ele.group, ele.period, ele.block))
self.mass.SetLabel("%.10g" % ele.mass)
self.eleshell.SetLabel(', '.join("%i" % i for i in ele.eleshells))
self.massnumber.SetLabel('%i A ' % ele.nominalmass)
self.protons.SetLabel('%i P ' % ele.protons)
self.neutrons.SetLabel('%i N ' % ele.neutrons)
self.electrons.SetLabel('%i e ' % ele.electrons)
self.oxistates.SetLabel(ele.oxistates)
self.atmrad.SetLabel(_u("%.10g \xc5 ") % ele.atmrad if ele.atmrad else
"")
self.eleneg.SetLabel("%.10g" % ele.eleneg if ele.eleneg else "")
self.ionpot.SetLabel(
"%.10g eV" % ele.ionenergy[0] if ele.ionenergy else "")
self.symbol.SetLabel(ele.symbol)
self.name.SetLabel(ele.name)
label = []
for orb in ele.eleconfig.split():
if not orb.startswith('[') and len(orb) > 2:
orb = orb[:2] + '<sup>' + orb[2:] + '</sup>'
label.append(orb)
label.append("<sup> </sup>") # fix ADJUST_MINSIZE
self.eleconfig.SetLabel(' '.join(label))
self.Thaw()
self.Layout()
class DetailsPanel(wx.Panel):
"""Element details panel."""
def __init__(self, *args, **kwds):
kwds["style"] = wx.NO_BORDER|wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
self.selected = -1
# create controls
self.names = LabeledCtrl(self, wx.ComboBox, "Element Name",
choices=[p.name for p in ELEMENTS],
style=wx.CB_READONLY|wx.CB_SORT, size=(1, -1))
self.symbols = LabeledCtrl(self, wx.ComboBox, "Symbol", '',
choices=[p.symbol for p in ELEMENTS],
style=wx.CB_READONLY|wx.CB_SORT, size=(1, -1))
self.numbers = LabeledCtrl(self, wx.ComboBox, "Number",
choices=["%s" % p.number for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.mass = LabeledCtrl(self, wx.ComboBox, "Relative Atomic Mass",
choices=["%-.10g" % p.mass for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.atmrad = LabeledCtrl(self, wx.ComboBox,
_u("Atomic Radius (\xc5)"),
choices=["%-.10g" % p.atmrad for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.covrad = LabeledCtrl(self, wx.ComboBox,
_u("Covalent Radius (\xc5)"),
choices=["%-.10g" % p.covrad for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.vdwrad = LabeledCtrl(self, wx.ComboBox,
_u("V.d.Waals Radius (\xc5)"),
choices=["%-.10g" % p.vdwrad for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.eleneg = LabeledCtrl(self, wx.ComboBox, "Electronegativity",
choices=["%-.10g" % p.eleneg for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.eleconfig = LabeledCtrl(self, wx.ComboBox, "e- Config",
choices=[p.eleconfig for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.eleshells = LabeledCtrl(self, wx.ComboBox, "Electrons per Shell",
choices=[', '.join("%i" % i for i in p.eleshells)
for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.oxistates = LabeledCtrl(self, wx.ComboBox, "Oxidation States",
choices=[p.oxistates for p in ELEMENTS],
style=wx.CB_READONLY, size=(1, -1))
self.ionpot = LabeledCtrl(self, wx.Choice,
"Ionization Potentials (eV)", choices=[], size=(1, -1))
self.isotopes = LabeledCtrl(self, wx.Choice, "Isotopes",
choices=[], size=(1, -1))
# layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer_top = wx.BoxSizer(wx.HORIZONTAL)
sizer_left = wx.BoxSizer(wx.VERTICAL)
sizer_right = wx.BoxSizer(wx.VERTICAL)
sizer_num = wx.BoxSizer(wx.HORIZONTAL)
style = wx.RIGHT|wx.BOTTOM|wx.EXPAND|wx.ADJUST_MINSIZE
sizer_left.Add(self.names, 0, style, SPACER)
sizer_left.Add(self.mass, 0, style, SPACER)
sizer_left.Add(self.atmrad, 0, style, SPACER)
sizer_left.Add(self.covrad, 0, style, SPACER)
sizer_left.Add(self.vdwrad, 0, style, SPACER)
sizer_left.Add(self.eleneg, 0, style, SPACER)
sizer_top.Add(sizer_left, 1, wx.LEFT|wx.RIGHT, 0)
style = wx.BOTTOM|wx.EXPAND|wx.ADJUST_MINSIZE
sizer_num.Add(self.symbols, 1, style, 0)
sizer_num.Add((SPACER, 5), 0, 0, 0)
sizer_num.Add(self.numbers, 1, style, 0)
sizer_right.Add(sizer_num, 0, style, SPACER)
sizer_right.Add(self.eleconfig, 0, style, SPACER)
sizer_right.Add(self.eleshells, 0, style, SPACER)
sizer_right.Add(self.oxistates, 0, style, SPACER)
sizer_right.Add(self.ionpot, 0, style, SPACER)
sizer_right.Add(self.isotopes, 0, style, SPACER)
sizer_top.Add(sizer_right, 1, wx.TOP|wx.RIGHT, 0)
sizer.Add(sizer_top, 1,
wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND|wx.ADJUST_MINSIZE, SPACER)
self.SetAutoLayout(True)
self.SetSizerAndFit(sizer, True)
sizer.SetSizeHints(self)
self.Layout()
# bind events
self.Bind(wx.EVT_COMBOBOX, self.OnSelectName, self.names.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelectSymbol, self.symbols.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.numbers.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.mass.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.atmrad.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.covrad.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.vdwrad.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.eleshells.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.eleneg.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.eleconfig.ctrl)
self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.oxistates.ctrl)
def SetSelection(self, select):
"""Set active element."""
if self.selected == select:
return
self.selected = select
ele = ELEMENTS[select+1]
self.names.ctrl.SetStringSelection(ele.name)
self.symbols.ctrl.SetStringSelection(ele.symbol)
self.numbers.ctrl.SetSelection(select)
self.mass.ctrl.SetSelection(select)
self.eleconfig.ctrl.SetSelection(select)
self.atmrad.ctrl.SetSelection(select)
self.covrad.ctrl.SetSelection(select)
self.vdwrad.ctrl.SetSelection(select)
self.eleneg.ctrl.SetSelection(select)
self.eleshells.ctrl.SetSelection(select)
self.oxistates.ctrl.SetSelection(select)
self.isotopes.ctrl.Clear()
for index, massnum in enumerate(sorted(ele.isotopes)):
iso = ele.isotopes[massnum]
self.isotopes.ctrl.Append("%3i: %8.4f , %8.4f%%" % (
massnum, iso.mass, iso.abundance*100.0))
if massnum == ele.nominalmass:
self.isotopes.ctrl.SetSelection(index)
self.ionpot.ctrl.Clear()
for ion in ele.ionenergy:
self.ionpot.ctrl.Append("%8.4f" % ion)
self.ionpot.ctrl.SetSelection(0)
def OnSelect(self, evt):
self.SetSelection(evt.GetSelection())
event = SelectionEvent(pteEVT_ELE_CHANGED, self.GetId(), self.selected)
self.GetEventHandler().ProcessEvent(event)
evt.Skip()
def OnSelectName(self, evt):
self.SetSelection(ELEMENTS[evt.GetString()].number - 1)
event = SelectionEvent(pteEVT_ELE_CHANGED, self.GetId(), self.selected)
self.GetEventHandler().ProcessEvent(event)
evt.Skip()
def OnSelectSymbol(self, evt):
self.SetSelection(ELEMENTS[evt.GetString()].number - 1)
event = SelectionEvent(pteEVT_ELE_CHANGED, self.GetId(), self.selected)
self.GetEventHandler().ProcessEvent(event)
evt.Skip()
class DecriptionPanel(wx.Panel):
"""Element description panel."""
def __init__(self, *args, **kwds):
kwds["style"] = wx.NO_BORDER|wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
self.selected = -1
self.description = wx.TextCtrl(self, -1, " \n \n",
style=wx.TE_MULTILINE|wx.TE_READONLY)
font = self.description.GetFont()
font.SetPointSize((font.GetPointSize() + 1))
self.description.SetFont(font)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.description, 1,
wx.TOP|wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND|wx.FIXED_MINSIZE,
SPACER)
self.SetAutoLayout(True)
self.SetSizerAndFit(sizer, True)
sizer.SetSizeHints(self)
self.Layout()
def SetSelection(self, select):
"""Set active element."""
if self.selected == select:
return
self.selected = select
ele = ELEMENTS[select + 1]
self.description.SetValue(ele.description)
class ElementButton(buttons.GenToggleButton):
"""Button representing chemical element."""
def __init__(self, *args, **kwds):
buttons.GenToggleButton.__init__(self, *args, **kwds)
self.color = wx.Colour(255, 255, 255)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
def OnEraseBackground(self, event):
pass
def SetButtonColour(self, color):
self.color = color
def OnPaint(self, event):
width, height = self.GetClientSizeTuple()
dc = wx.BufferedPaintDC(self)
brush = wx.Brush(self.GetBackgroundColour(), wx.SOLID)
if wx.Platform == "__WXMAC__":
brush.MacSetTheme(1) # kThemeBrushDialogBackgroundActive
dc.SetBackground(brush)
dc.SetPen(wx.TRANSPARENT_PEN)
dc.SetBrush(wx.Brush(self.color if self.up else 'WHITE', wx.SOLID))
dc.Clear()
dc.DrawRectanglePointSize((1, 1), (width - 2, height - 2))
if self.up:
self.DrawBezel(dc, 0, 0, width - 1, height - 1)
self.DrawLabel(dc, width, height)
if (self.hasFocus and self.useFocusInd):
self.DrawFocusIndicator(dc, width, height)
def DrawLabel(self, dc, width, height):
font = self.GetFont()
font.SetWeight(wx.FONTWEIGHT_BOLD)
dc.SetFont(font)
if self.IsEnabled():
dc.SetTextForeground(self.GetForegroundColour())
else:
dc.SetTextForeground(wx.SystemSettings.GetColour(
wx.SYS_COLOUR_GRAYTEXT))
label = self.GetLabel()
txtwidth, txtheight = dc.GetTextExtent(label)
xpos = (width - txtwidth) // 2
ypos = (height*0.75 - txtheight) // 2 - 1
dc.DrawText(label, xpos, ypos)
font.SetWeight(wx.FONTWEIGHT_LIGHT)
font.SetPointSize((font.GetPointSize()*6) // 8)
dc.SetFont(font)
label = "%i" % (self.GetId() - 100)
txtwidth, txtheight = dc.GetTextExtent(label)
dc.DrawText(label, (width-txtwidth)//2, 4+ypos+(height-txtheight)//2)
class LabeledCtrl(wx.BoxSizer):
"""BoxSizer containing label, control, and unit."""
def __init__(self, parent, control, label, unit=None, space=" ",
*args, **kwds):
wx.BoxSizer.__init__(self, wx.HORIZONTAL)
self.label = wx.StaticText(parent, -1, label + space)
self.ctrl = control(parent, -1, *args, **kwds)
self.Add(self.label, 0, wx.ALIGN_CENTER_VERTICAL|wx.FIXED_MINSIZE)
self.Add(self.ctrl, 1, (wx.LEFT|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|
wx.ALIGN_RIGHT|wx.ADJUST_MINSIZE), 0)
if unit:
self.unit = wx.StaticText(parent, -1, unit)
self.Add(self.unit, 0,
wx.RIGHT|wx.ALIGN_CENTER_VERTICAL|wx.FIXED_MINSIZE, 0)
else:
self.unit = None
class StaticFancyText(fancytext.StaticFancyText):
"""StaticFancyText with SetLabel function."""
def SetLabel(self, label):
bmp = fancytext.RenderToBitmap(
label, wx.Brush(self.GetBackgroundColour(), wx.SOLID))
self.SetBitmap(bmp)
class DisclosureCtrl(buttons.GenBitmapTextToggleButton):
"""Disclosure triangle button."""
bmp0 = (b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\r\x00\x00'
b'\x00\r\x08\x06\x00\x00\x00r\xeb\xe4|\x00\x00\x00\x04sBIT'
b'\x08\x08\x08\x08|\x08d\x88\x00\x00\x00\xd5IDAT(\x91\x9d'
b'\x921n\x83@\x10E\xdf.!\x96\x9c\x90P"\xd9\x86\x92\x82\x03p'
b'\x02h\xa9i9A\xe2\xb38)9\x02w\xc0\t\x94I\xa0H\xd2\xc7'
b'\x96(\x918\xc0\xa6Z\x17\x91\x05&_\x1a\xe9k4O\xfa3\x1a!'
b'\xa4\xc1\\Im>\xde\xdf\xd4l\xa8,K\x9e\x9fv\xeax\xf8\x99\x84'
b'\x85\x8e\xb7}|P\x00\xb6m\x13\x04\x01q\x1cc\xdd\xdd\x8bs\xd0'
b'\xd5\xdfF\xdf\xf7TUE\xdb\xb6\xbc\xbe\xecU\x18\x86\x98\xd7'
b'\x0b1\ni\r\xc3@Q\x14\xd4u\xcd\xf7\xd7\xa7r]\x97\xe5\xcd'
b'\xad\x18\x85\xb4\xba\xae#\xcfs|\xdf?\xf5\xe4\xc8<\x00\x8e'
b'\xe3\x90e\x19i\x9aN\xc7\xb3,\x8b(\x8a\xb8h\xa7Y\xd7'
b'\xf3<\x0f\xd34I\x92\x84\xd5zsv\xf8$!\r\x844h\x9aFi?Y\xff'
b'\xf9\xbd_\xd7\x8c7Z\xc0k\x8d8\x00\x00\x00\x00IEND\xaeB`\x82')
bmp1 = (b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\r\x00\x00'
b'\x00\r\x08\x06\x00\x00\x00r\xeb\xe4|\x00\x00\x00\x04sBIT'
b'\x08\x08\x08\x08|\x08d\x88\x00\x00\x00\xc1IDAT(\x91\x9d\xd2;'
b'\x8e\xc20\x10\x80\xe1\x7fB\x0c\x95\xc1\xa5%\xc0)S\xb8I\xd2'
b'\xb8Le\x97\xf6\x99s\x81\xdd\xbdBN\xb2\xdb!Y\t\xac`\xbay|'
b'\xa3)F\xa49\xf0n4o\x8bOQ\x0b\xf0\xf3\xfd\xf5\xbb,\x0b\xeb'
b'\xba>\x1d\xec\xba\x8ey\x9e\x19\xc6I\x1a\x80a\x9cD)\xf5r'
b'\xbbR\x8aa\x9c\xa4:\xaf\x94\x821f\x17\x18c(\xa5<\xf2\x07'
b'\xba\xde\xee\xe2\xbd\xdfE\xde{\xae\xb7\xbbl\x10@J\t\xadu\x05'
b'\xb4\xd6\xa4\x94\xaaZ\x85\xf4\xf9"1\xc6j \xc6\x88>_\xe4)\x02'
b'\x08!`\xad\x05\xc0ZK\x08as\xee\x06\xa9\xe3Ir\xce\xb4mK\xce'
b'\x19u<\xc9\xbf\x08\xc09G\xdf\xf78\xe7\xf6\xda\xc8\'\xbf\xf7'
b'\x07\x13\x12\x18B\x17\x9fx\xa0\x00\x00\x00\x00IEND\xaeB`\x82')
def __init__(self, parent, winid, label, *args, **kwds):
kwds["style"] = wx.BORDER_NONE|wx.BU_EXACTFIT
buttons.GenBitmapTextToggleButton.__init__(self, parent, winid, None,
label, *args, **kwds)
if isinstance(self.bmp0, type(b'')):
self.__class__.bmp0 = wx.BitmapFromImage(wx.ImageFromStream(
io.BytesIO(self.bmp0)))
self.__class__.bmp1 = wx.BitmapFromImage(wx.ImageFromStream(
io.BytesIO(self.bmp1)))
self.SetBitmapLabel(self.bmp0)
self.SetBitmapSelected(self.bmp1)
if not label:
self.SetSize(self.bmp0.GetSize())
else:
self.SetBestSize()
self.labelDelta = 0
self.useFocusInd = False
self.SetToolTipString('Show')
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
def OnEraseBackground(self, event):
pass
def Notify(self):
wx.lib.buttons.GenBitmapTextToggleButton.Notify(self)
self.SetToolTipString("%s" % ('Show' if self.up else 'Hide'))
def DoGetBestSize(self):
width, height, usemin = self._GetLabelSize()
return width + 5, height + 4
def OnPaint(self, event):
width, height = self.GetClientSizeTuple()
dc = wx.BufferedPaintDC(self)
brush = None
bgcol = self.GetBackgroundColour()
brush = wx.Brush(bgcol, wx.SOLID)
defattr = self.GetDefaultAttributes()
if self.style & wx.BORDER_NONE and bgcol == defattr.colBg:
defattr = self.GetParent().GetDefaultAttributes()
if self.GetParent().GetBackgroundColour() == defattr.colBg:
if wx.Platform == "__WXMSW__":
if self.DoEraseBackground(dc):
brush = None
elif wx.Platform == "__WXMAC__":
brush.MacSetTheme(1)
else:
bgcol = self.GetParent().GetBackgroundColour()
brush = wx.Brush(bgcol, wx.SOLID)
if brush is not None:
dc.SetBackground(brush)
dc.Clear()
self.DrawLabel(dc, width, height)
def DrawLabel(self, dc, width, height, center=False):
bmp = self.bmpLabel
if bmp is not None:
if self.bmpDisabled and not self.IsEnabled():
bmp = self.bmpDisabled
if self.bmpFocus and self.hasFocus:
bmp = self.bmpFocus
if self.bmpSelected and not self.up:
bmp = self.bmpSelected
bmpwidth, bmpheight = bmp.GetWidth(), bmp.GetHeight()
hasmask = bmp.GetMask() is not None
else:
bmpwidth = bmpheight = 0
dc.SetFont(self.GetFont())
color = (self.GetForegroundColour() if self.IsEnabled() else
wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
dc.SetTextForeground(color)
label = self.GetLabel()
txtwidth, txtheight = dc.GetTextExtent(label)
# center bitmap and text
xpos = (width - bmpwidth - txtwidth) // 2 if center else 0
if bmp is not None:
dc.DrawBitmap(bmp, xpos, (height - bmpheight) // 2, hasmask)
xpos += 5
dc.DrawText(label, xpos + bmpwidth, (height - txtheight) // 2)
class SelectionEvent(wx.PyCommandEvent):
"""Notification of changed element."""
def __init__(self, evtType, winid, sel):
wx.PyCommandEvent.__init__(self, evtType, winid)
self.selection = sel
def SetSelection(self, select):
self.selection = select
def GetSelection(self):
return self.selection
pteEVT_ELE_CHANGED = wx.NewEventType()
EVT_ELE_CHANGED = wx.PyEventBinder(pteEVT_ELE_CHANGED, 1)
SPACER = 12 if wx.Platform == "__WXMAC__" else 10
BORDER = 22 if wx.Platform == "__WXMAC__" else 10
COLORS = {
1: (0x99, 0xff, 0x99), # Nonmetals
2: (0xc0, 0xff, 0xff), # Noble gases
3: (0xff, 0x99, 0x99), # Alkali metals
4: (0xff, 0xde, 0xad), # Alkaline earth metals
5: (0xcc, 0xcc, 0x99), # Metalloids
6: (0xff, 0xff, 0x99), # Halogens
7: (0xcc, 0xcc, 0xcc), # Poor metals
8: (0xff, 0xc0, 0xc0), # Transition metals
9: (0xff, 0xbf, 0xff), # Lanthanides
10: (0xff, 0x99, 0xcc), # Actinides
}
_u = (lambda x: x.decode('latin-1')) if sys.version[0] == '2' else str
if __name__ == "__main__":
MainApp(0).MainLoop()
|
"use strict";
/**
* Login API
*
* Provides various utilities for managing the login process, including
* login/logout and import/export of appstate files.
*
* Encapsulates the login by caching the appstate in memory.
*
* @module login
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMemCache = exports.convertToFile = exports.convert = exports.logout = exports.loadLogin = exports.dumpLogin = exports.login = void 0;
var facebook_chat_api_1 = __importDefault(require("facebook-chat-api")); // Chat API
var fs_1 = require("fs");
var argparse_1 = require("argparse");
var memjs_1 = require("memjs");
// Default behavior: minimal logging and auto-approve recent logins
var defaultOptions = {
"logLevel": "error",
"forceLogin": true,
// TODO: Get rid of this option. We currently have to use this outdated user agent to force Facebook
// to give us an older version of the login page that doesn't include new checks that break the API.
"userAgent": "Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Mobile Safari/537.36"
};
var mem;
/**
* Call this to initialize the login module and log into Facebook using
* [facebook-chat-api](https://github.com/Schmavery/facebook-chat-api).
* See examples/ for example usage.
*
* @param credentials
* @param callback called after login completed (successfully or unsuccessfully)
* @param [forceCreds=false] if true, forces a login with credentials even if appstate exists
* @param [options=defaultOptions] any options you wish to pass to the API on login;
* by default, sets `logLevel` to `error` and `forceLogin` to `true` (auto-approves errors asking
* for approval of recent logins for simplicity)
*/
var login = function (credentials, callback, forceCreds, options) {
if (forceCreds === void 0) { forceCreds = false; }
if (options === void 0) { options = defaultOptions; }
// Initialize mem variable for external storage API (Memcachier)
mem = memjs_1.Client.create(credentials.MEMCACHIER_SERVERS, {
username: credentials.MEMCACHIER_USERNAME,
password: credentials.MEMCACHIER_PASSWORD
});
// Login utility funcs
function withAppstate(appstate, callback) {
console.log("Logging in with saved appstate...");
facebook_chat_api_1.default({
appState: JSON.parse(appstate)
}, options, function (err, api) {
if (err) {
withCreds(callback);
}
else {
callback(err, api);
}
});
}
function withCreds(callback) {
console.log("Logging in with credentials...");
if (!credentials.FACEBOOK_EMAIL || !credentials.FACEBOOK_PASSWORD) {
return console.error("Fatal error: no login credentials provided");
}
facebook_chat_api_1.default({
email: credentials.FACEBOOK_EMAIL,
password: credentials.FACEBOOK_PASSWORD
}, options, function (err, api) {
if (err)
return console.error("Fatal error: failed login with credentials");
mem.set("appstate", JSON.stringify(api.getAppState()), {}, function (merr) {
if (err) {
return console.error(merr);
}
else {
callback(err, api);
}
});
});
}
if (forceCreds) {
// Force login with credentials
withCreds(callback);
}
else {
// Use stored appstate if exists, otherwise fallback to creds
mem.get("appstate", function (err, val) {
if (!err && val) {
withAppstate(val.toString(), callback);
}
else {
withCreds(callback);
}
});
}
};
exports.login = login;
/**
* Dumps the current login into a specified file.
*
* @param filename Name of the file specifying where to store the login
* @param callback Callback to use after writing the file
*/
var dumpLogin = function (filename, callback) {
mem.get("appstate", function (err, val) {
if (!err && val) {
fs_1.writeFileSync(filename, val.toString());
}
callback(err);
});
};
exports.dumpLogin = dumpLogin;
/**
* Reads a new login into memory from a file.
* @param filename Name of the file specifying where the imported login
* is stored
* @param callback Callback to use after reading the login
*/
var loadLogin = function (filename, callback) {
fs_1.readFile(filename, function (err, val) {
if (!err) {
mem.set("appstate", JSON.stringify(JSON.parse(val.toString())), {});
}
callback(err);
});
};
exports.loadLogin = loadLogin;
/**
* Logs out of Facebook.
* @param callback
*/
var logout = function (callback) {
mem.delete("appstate", function (err) {
var success = true;
if (err) {
console.log("Error logging out: " + err);
success = false;
}
else {
console.log("Logged out successfully.");
}
callback(err, success);
});
};
exports.logout = logout;
/**
* Converts a (NodeJS) facebook-chat-api appstate into a (Python) fbchat
* session. See the examples/ directory for how this can be used to create
* an fbchat bot with BotCore.
*
* @param filename Name of the file whose location contains the
* appstate data to be converted
* @param callback Callback to use after conversion completed,
* passed the converted session
*/
var convert = function (filename, callback) {
fs_1.readFile(filename, function (err, file) {
if (err) {
callback(err);
}
else {
// Extract the required information from the appstate
var data_1 = JSON.parse(file.toString());
var attrs = ["c_user", "datr", "fr", "sb", "spin", "xs"];
var output = attrs.reduce(function (obj, key) {
obj[key] = searchAttribute(data_1, key);
return obj;
}, {});
output["noscript"] = "1"; // Special attr
callback(null, output);
}
});
};
exports.convert = convert;
/**
* A variant of `convert` that directly outputs the converted session to a file.
*
* @param appstate Location of appstate to be converted
* @param output Where to place the converted session
* @param callback Callback called after conversion
*/
var convertToFile = function (appstate, output, callback) {
exports.convert(appstate, function (err, session) {
if (err) {
callback(err);
}
else {
fs_1.writeFile(output, JSON.stringify(session), null, callback);
}
});
};
exports.convertToFile = convertToFile;
/**
* Exposes the underlying memjs memcache instance, which can be used for
* temporary storage. Use wisely, or you may break your BotCore installation!
*
* > NOTE: if you call this before logging in with {@link login},
* it will return nothing; the memcache is not initialized until you log in.
*
* @returns {Object} The underlying BotCore [memjs](https://memjs.netlify.app)
* instance
*/
var getMemCache = function () {
return mem;
};
exports.getMemCache = getMemCache;
/**
* facebook-chat-api appstates are an array of objects containing "key" and
* "value" keys and additional properties (that the Python API doesn't use).
*
* This function searches and extracts the value for the given key, discarding
* the other information.
*
* @param data facebook-chat-api appstate
* @param key The key to locate
* @returns {string} The value of the key (or null if not found)
*/
function searchAttribute(data, key) {
for (var i = 0; i < data.length; i++) {
if (data[i].key == key) {
return data[i].value;
}
}
return "";
}
if (require.main === module) {
var parser = new argparse_1.ArgumentParser({ add_help: true });
parser.add_argument("--MEMCACHIER-USERNAME", { required: true });
parser.add_argument("--MEMCACHIER-PASSWORD", { required: true });
parser.add_argument("--MEMCACHIER-SERVERS", { required: true });
parser.add_argument("--logout", { nargs: 0 });
parser.add_argument("--dump-login", { nargs: 0 });
parser.add_argument("--load-login", { nargs: 0 });
parser.add_argument("--convert-login", { nargs: 0 });
var args_1 = parser.parse_args();
exports.login(args_1, function () {
if (args_1.logout !== null) {
exports.logout(function () {
process.exit();
});
}
else if (args_1.dump_login !== null) {
exports.dumpLogin("appstate.json", function () {
process.exit();
});
}
else if (args_1.load_login !== null) {
exports.loadLogin("appstate.json", function () {
process.exit();
});
}
else if (args_1.convert_login !== null) {
exports.convertToFile("appstate.json", "session.txt", function () {
process.exit();
});
}
else {
process.exit();
}
});
}
|
"""
tsv.py
~~~~~~~~~~~~
Save/Read to 'data/XXXX.tsv' file.
:copyright: (c) 2018 by Steve ([email protected])
:license: see LICENSE for more details.
"""
import pprint
# base of data folder
DATA_BASE = 'data/'
FILE_EXT = '.tsv'
# save lines to tsv
#TODO - if type of lines is numpy, then use other-way.
def save_list_to_tsv(mid, lines = []):
# import pandas as pd
# import numpy as np
import csv
fname = DATA_BASE + mid + FILE_EXT
print('> file.save =', fname)
# pprint.pprint(lines)
print('> lines.len =', len(lines))
# np.savetxt(fname, lines, fmt='%s', delimiter='\t')
with open(fname, 'w', encoding='utf-8') as f:
wr = csv.writer(f, delimiter='\t')
wr.writerows(lines)
# load lines from tsv
def load_list_from_tsv(mid):
# import pandas as pd
# import numpy as np
import csv
fname = DATA_BASE + mid + FILE_EXT
print('> file.read =', fname)
# lines = np.loadtxt(fname, delimiter='\t')
# lines = pd.read_csv(fname, sep='\t')
lines = []
with open(fname, 'r', encoding='utf-8') as f:
rdr = csv.reader(f, delimiter='\t')
lines = list(rdr)
print('> lines.len =', len(lines))
return lines
|
export default {
"limit": 100,
"total_students": 1,
"students_with_high_absences": [
{
"count": 4,
"student": {
"id": 2,
"grade": "9",
"first_name": "Mari",
"last_name": "Kenobi",
"house": "Beacon"
}
}
]
}; |
/* global Module */
/* Magic Mirror 2
* Module: MMM-Modulebar
*
* By Erik Pettersson
* Based on the TouchNavigation Module by Brian Janssen
*
* MIT Licensed.
*/
//var request = require('request');
Module.register("MMM-Modulebar1",{
requiresVersion: "2.1.0",
defaults: {
// Allow the module to force modules to be shown (if hidden and locked by another module ex. profile-switcher).
allowForce: false,
// Determines if the border around the buttons should be shown.
showBorder: true,
// The minimum width for all the buttons.
minWidth: "0px",
// The minimum height for all the buttons.
minHeight: "0px",
// The location of the symbol relative to the text. Options: left, right, top or bottom
picturePlacement: "left",
// The direction of the bar. Options: row, column, row-reverse or column-reverse
direction: "row",
// The speed of the hide and show animation.
animationSpeed: 1000,
// The default button 1. Add your buttons in the config.
buttons: {
"1": {
// The modules exact name to be affected.
module: "clock",
// The text to be displayed in the button.
text: "Clock",
// Then symbol from font-awesome!
symbol: "clock-o"
}
}
},
// Define required styles.
getStyles: function(){
return ["font-awesome.css", "MMM-Modulebar1.css"];
},
// Override dom generator.
getDom: function() {
var menu = document.createElement("span");
menu.className = "modulebar-menu";
menu.id = this.identifier + "_menu";
menu.style.flexDirection = this.config.direction;
// Sends each button to the "createButton" function be created.
for (var num in this.config.buttons) {
menu.appendChild(this.createButton(this, num, this.config.buttons[num], this.config.picturePlacement));
}
return menu;
},
// 버튼 생성
createButton: function (self, num, data, placement) {
// span Element 생성
var item = document.createElement("span");
// 모듈 id 설정
item.id = self.identifier + "_button_" + num;
// 모든 모듈 클래스 지정
item.className = "modulebar-button";
//최소의 넓이 높이 지정.
item.style.minWidth = self.config.minWidth;
item.style.minHeight = self.config.minHeight;
// 매직미러에 로드된 모든 모듈들을 호출
var modules = MM.getModules();
// 클릭시
item.addEventListener("click", function () {
// 모든 모듈체크
for (var i = 0; i < modules.length; i++) {
// 현재 모듈 확인
if (modules[i].name === data.module) {
var idnr = modules[i].data.identifier.split("_");
console.log("idnr : "+idnr+"idnum"+data.idnum);
if (idnr[1] == data.idnum || data.idnum == null) {
// 모듈이 숨겨져있는 상태일때
if (modules[i].hidden) {
// Showurl 설정 확인
if (data.showUrl != null) {
//Show url
fetch(data.showUrl);
console.log("Visiting show URL: "+data.showUrl);
}
//한 프레임에 두가지이상의 모듈이 뜨지 않게 하기.
if (modules[i].name == 'MMM-Modulebar') {
console.log("Hiding opend "+ modules[i-3].name+" ID: "+idnr[1]);
modules[0].hide(self.config.animationSpeed, {force: self.config.allowForce});
}
else if(modules[i].name == 'MMM-iFrame') {
console.log("Hiding opend "+ modules[i+5].name+" ID: "+idnr[1]);
//modules[i+5].hide(self.config.animationSpeed, {force: self.config.allowForce});
}
// 모듈 보이기
modules[i].show(self.config.animationSpeed, {force: self.config.allowForce});
console.log("Showing "+modules[i].name+" ID: "+idnr[1]);
}else{
// 모듈이 켜있는 상태일때
modules[i].hide(self.config.animationSpeed, {force: self.config.allowForce});
console.log("Hiding "+modules[i].name+" ID: "+idnr[1]);
// hideURL이 설정되 있을 때
if (data.hideUrl != null) {
fetch(data.hideUrl);
console.log("Visiting hide URL: "+data.hideUrl);
}
}
}
}
}
});
// 버튼 배열
item.style.flexDirection = {
"right" : "row-reverse",
"left" : "row",
"top" : "column",
"bottom" : "column-reverse"
}[placement];
// Sets the border around the symbol/picture/text to black.
if (!self.config.showBorder) {
item.style.borderColor = "black";
}
// Adds the Font-Awesome symbol if specified.
if (data.symbol) {
var symbol = document.createElement("span");
symbol.className = "modulebar-picture fa fa-" + data.symbol;
// Sets the size on the symbol if specified.
if (data.size) {
symbol.className += " fa-" + data.size;
symbol.className += data.size == 1 ? "g" : "x";
}
// Align the symbol with a margin.
if (data.text && placement === "left") {
symbol.style.marginRight = "4px";
}
// Adds the symbol to the item.
item.appendChild(symbol);
// Adds a picture if specified.
} else if (data.img) {
var image = document.createElement("img");
image.className = "modulebar-picture";
image.src = data.img;
// Sets the size of the picture if specified.
if (data.width) image.width = data.width;
if (data.height) image.height = data.height;
// Align the picture with a margin.
if (data.text && placement === "left") {
image.style.marginRight = "4px";
}
// Adds the picture to the item.
item.appendChild(image);
}
// Adds the text if specified.
if (data.text) {
var text = document.createElement("span");
text.className = "modulebar-text";
text.innerHTML = data.text;
// Align the text with a margin.
if ((data.symbol || data.img) && placement === "right") {
text.style.marginRight = "4px";
}
// Adds the text to the item.
item.appendChild(text);
}
// All done. :)
return item;
}
});
|
import React from "react";
import PropTypes from "prop-types";
import { Container, Grid, TimeSpan } from "basis";
import KitchenSinkLayout from "./KitchenSinkLayout";
import KitchenSinkForm from "./KitchenSinkForm";
function FormWithTimeSpan({
label,
initialValue = {
years: "",
months: ""
},
disabled,
helpText,
optional,
__internal__yearsFocus,
__internal__monthsFocus,
submitOnMount
}) {
return (
<KitchenSinkForm
initialValues={{ liveInCurrentAddress: initialValue }}
submitOnMount={submitOnMount}
>
<TimeSpan
name="liveInCurrentAddress"
label={label}
disabled={disabled}
helpText={helpText}
optional={optional}
__internal__yearsFocus={__internal__yearsFocus}
__internal__monthsFocus={__internal__monthsFocus}
/>
</KitchenSinkForm>
);
}
FormWithTimeSpan.propTypes = {
label: PropTypes.string.isRequired,
initialValue: PropTypes.shape({
years: PropTypes.string.isRequired,
months: PropTypes.string.isRequired
}),
disabled: PropTypes.bool,
helpText: PropTypes.string,
optional: PropTypes.bool,
__internal__yearsFocus: PropTypes.bool,
__internal__monthsFocus: PropTypes.bool,
submitOnMount: PropTypes.bool
};
function KitchenSinkTimeSpan() {
return (
<KitchenSinkLayout name="TimeSpan">
<Container width="320" padding="4" bg="white">
<Grid rowsGap="8">
<FormWithTimeSpan label="Grey" />
<FormWithTimeSpan label="Optional" optional />
<FormWithTimeSpan
label="Years"
initialValue={{
years: "2",
months: ""
}}
/>
<FormWithTimeSpan
label="Months"
initialValue={{
years: "",
months: "3"
}}
/>
<FormWithTimeSpan
label="Years and months"
initialValue={{
years: "1",
months: "1"
}}
/>
<FormWithTimeSpan label="With errors" submitOnMount />
</Grid>
</Container>
<Container width="320" padding="4" bg="grey.t05">
<Grid rowsGap="8">
<FormWithTimeSpan label="Years focus" __internal__yearsFocus />
<FormWithTimeSpan label="Months focus" __internal__monthsFocus />
<FormWithTimeSpan
label="Disabled with help text"
helpText="Help text goes here"
disabled
/>
</Grid>
</Container>
</KitchenSinkLayout>
);
}
export default KitchenSinkTimeSpan;
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => {
const core = window.Deno.core;
const { pathFromURL } = window.__bootstrap.util;
const build = window.__bootstrap.build.build;
function chmodSync(path, mode) {
core.jsonOpSync("op_chmod_sync", { path: pathFromURL(path), mode });
}
async function chmod(path, mode) {
await core.jsonOpAsync("op_chmod_async", { path: pathFromURL(path), mode });
}
function chownSync(
path,
uid,
gid,
) {
core.jsonOpSync("op_chown_sync", { path: pathFromURL(path), uid, gid });
}
async function chown(
path,
uid,
gid,
) {
await core.jsonOpAsync(
"op_chown_async",
{ path: pathFromURL(path), uid, gid },
);
}
function copyFileSync(
fromPath,
toPath,
) {
core.jsonOpSync("op_copy_file_sync", {
from: pathFromURL(fromPath),
to: pathFromURL(toPath),
});
}
async function copyFile(
fromPath,
toPath,
) {
await core.jsonOpAsync("op_copy_file_async", {
from: pathFromURL(fromPath),
to: pathFromURL(toPath),
});
}
function cwd() {
return core.jsonOpSync("op_cwd");
}
function chdir(directory) {
core.jsonOpSync("op_chdir", directory);
}
function makeTempDirSync(options = {}) {
return core.jsonOpSync("op_make_temp_dir_sync", options);
}
function makeTempDir(options = {}) {
return core.jsonOpAsync("op_make_temp_dir_async", options);
}
function makeTempFileSync(options = {}) {
return core.jsonOpSync("op_make_temp_file_sync", options);
}
function makeTempFile(options = {}) {
return core.jsonOpAsync("op_make_temp_file_async", options);
}
function mkdirArgs(path, options) {
const args = { path: pathFromURL(path), recursive: false };
if (options != null) {
if (typeof options.recursive == "boolean") {
args.recursive = options.recursive;
}
if (options.mode) {
args.mode = options.mode;
}
}
return args;
}
function mkdirSync(path, options) {
core.jsonOpSync("op_mkdir_sync", mkdirArgs(path, options));
}
async function mkdir(
path,
options,
) {
await core.jsonOpAsync("op_mkdir_async", mkdirArgs(path, options));
}
function readDirSync(path) {
return core.jsonOpSync("op_read_dir_sync", pathFromURL(path))[
Symbol.iterator
]();
}
function readDir(path) {
const array = core.jsonOpAsync(
"op_read_dir_async",
pathFromURL(path),
);
return {
async *[Symbol.asyncIterator]() {
yield* await array;
},
};
}
function readLinkSync(path) {
return core.jsonOpSync("op_read_link_sync", pathFromURL(path));
}
function readLink(path) {
return core.jsonOpAsync("op_read_link_async", pathFromURL(path));
}
function realPathSync(path) {
return core.jsonOpSync("op_realpath_sync", path);
}
function realPath(path) {
return core.jsonOpAsync("op_realpath_async", path);
}
function removeSync(
path,
options = {},
) {
core.jsonOpSync("op_remove_sync", {
path: pathFromURL(path),
recursive: !!options.recursive,
});
}
async function remove(
path,
options = {},
) {
await core.jsonOpAsync("op_remove_async", {
path: pathFromURL(path),
recursive: !!options.recursive,
});
}
function renameSync(oldpath, newpath) {
core.jsonOpSync("op_rename_sync", { oldpath, newpath });
}
async function rename(oldpath, newpath) {
await core.jsonOpAsync("op_rename_async", { oldpath, newpath });
}
function parseFileInfo(response) {
const unix = build.os === "darwin" || build.os === "linux";
return {
isFile: response.isFile,
isDirectory: response.isDirectory,
isSymlink: response.isSymlink,
size: response.size,
mtime: response.mtime != null ? new Date(response.mtime) : null,
atime: response.atime != null ? new Date(response.atime) : null,
birthtime: response.birthtime != null
? new Date(response.birthtime)
: null,
// Only non-null if on Unix
dev: unix ? response.dev : null,
ino: unix ? response.ino : null,
mode: unix ? response.mode : null,
nlink: unix ? response.nlink : null,
uid: unix ? response.uid : null,
gid: unix ? response.gid : null,
rdev: unix ? response.rdev : null,
blksize: unix ? response.blksize : null,
blocks: unix ? response.blocks : null,
};
}
function fstatSync(rid) {
return parseFileInfo(core.jsonOpSync("op_fstat_sync", rid));
}
async function fstat(rid) {
return parseFileInfo(await core.jsonOpAsync("op_fstat_async", rid));
}
async function lstat(path) {
const res = await core.jsonOpAsync("op_stat_async", {
path: pathFromURL(path),
lstat: true,
});
return parseFileInfo(res);
}
function lstatSync(path) {
const res = core.jsonOpSync("op_stat_sync", {
path: pathFromURL(path),
lstat: true,
});
return parseFileInfo(res);
}
async function stat(path) {
const res = await core.jsonOpAsync("op_stat_async", {
path: pathFromURL(path),
lstat: false,
});
return parseFileInfo(res);
}
function statSync(path) {
const res = core.jsonOpSync("op_stat_sync", {
path: pathFromURL(path),
lstat: false,
});
return parseFileInfo(res);
}
function coerceLen(len) {
if (len == null || len < 0) {
return 0;
}
return len;
}
function ftruncateSync(rid, len) {
core.jsonOpSync("op_ftruncate_sync", { rid, len: coerceLen(len) });
}
async function ftruncate(rid, len) {
await core.jsonOpAsync("op_ftruncate_async", { rid, len: coerceLen(len) });
}
function truncateSync(path, len) {
core.jsonOpSync("op_truncate_sync", { path, len: coerceLen(len) });
}
async function truncate(path, len) {
await core.jsonOpAsync("op_truncate_async", { path, len: coerceLen(len) });
}
function umask(mask) {
return core.jsonOpSync("op_umask", mask);
}
function linkSync(oldpath, newpath) {
core.jsonOpSync("op_link_sync", { oldpath, newpath });
}
async function link(oldpath, newpath) {
await core.jsonOpAsync("op_link_async", { oldpath, newpath });
}
function toUnixTimeFromEpoch(value) {
if (value instanceof Date) {
const time = value.valueOf();
const seconds = Math.trunc(time / 1e3);
const nanoseconds = Math.trunc(time - (seconds * 1e3)) * 1e6;
return [
seconds,
nanoseconds,
];
}
const seconds = value;
const nanoseconds = 0;
return [
seconds,
nanoseconds,
];
}
function futimeSync(
rid,
atime,
mtime,
) {
core.jsonOpSync("op_futime_sync", {
rid,
atime: toUnixTimeFromEpoch(atime),
mtime: toUnixTimeFromEpoch(mtime),
});
}
async function futime(
rid,
atime,
mtime,
) {
await core.jsonOpAsync("op_futime_async", {
rid,
atime: toUnixTimeFromEpoch(atime),
mtime: toUnixTimeFromEpoch(mtime),
});
}
function utimeSync(
path,
atime,
mtime,
) {
core.jsonOpSync("op_utime_sync", {
path,
atime: toUnixTimeFromEpoch(atime),
mtime: toUnixTimeFromEpoch(mtime),
});
}
async function utime(
path,
atime,
mtime,
) {
await core.jsonOpAsync("op_utime_async", {
path,
atime: toUnixTimeFromEpoch(atime),
mtime: toUnixTimeFromEpoch(mtime),
});
}
function symlinkSync(
oldpath,
newpath,
options,
) {
core.jsonOpSync("op_symlink_sync", { oldpath, newpath, options });
}
async function symlink(
oldpath,
newpath,
options,
) {
await core.jsonOpAsync("op_symlink_async", { oldpath, newpath, options });
}
function fdatasyncSync(rid) {
core.jsonOpSync("op_fdatasync_sync", rid);
}
async function fdatasync(rid) {
await core.jsonOpAsync("op_fdatasync_async", rid);
}
function fsyncSync(rid) {
core.jsonOpSync("op_fsync_sync", rid);
}
async function fsync(rid) {
await core.jsonOpAsync("op_fsync_async", rid);
}
window.__bootstrap.fs = {
cwd,
chdir,
chmodSync,
chmod,
chown,
chownSync,
copyFile,
copyFileSync,
makeTempFile,
makeTempDir,
makeTempFileSync,
makeTempDirSync,
mkdir,
mkdirSync,
readDir,
readDirSync,
readLinkSync,
readLink,
realPathSync,
realPath,
remove,
removeSync,
renameSync,
rename,
fstatSync,
fstat,
lstat,
lstatSync,
stat,
statSync,
ftruncate,
ftruncateSync,
truncate,
truncateSync,
umask,
link,
linkSync,
futime,
futimeSync,
utime,
utimeSync,
symlink,
symlinkSync,
fdatasync,
fdatasyncSync,
fsync,
fsyncSync,
};
})(this);
|
import React, { useEffect, useMemo } from 'react'
import { Button } from 'antd-mobile'
import { SvgIcon, StakingTokenItem, Toast } from '@/common'
import { I18n, Base } from '@tangle-pay/common'
import { useStore } from '@tangle-pay/store'
import { useGetNodeWallet } from '@tangle-pay/store/common'
import { useGetParticipationEvents, useGetRewards } from '@tangle-pay/store/staking'
import _get from 'lodash/get'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import advancedFormat from 'dayjs/plugin/advancedFormat'
dayjs.extend(advancedFormat)
dayjs.extend(utc)
const AmountCon = ({ amountList }) => {
return (
<div className='p20'>
<div className='fz14 fw600'>{I18n.t('staking.amount')}</div>
{amountList.map((e, i) => {
return (
<div key={i} className='flex row jsb ac mt15'>
<div className='flex row ac'>
<StakingTokenItem coin={e.token} label={`${Base.formatNum(e.amount)}Mi`} />
<div className='fz12 ml5 cS'>{e.statusStr}</div>
</div>
{!!e.onPress && (
<div>
<Button
disabled={e.btnDis}
onClick={e.onPress}
className='border'
color='primary'
size='middle'
style={{
'--border-radius': '20px',
borderColor: e.borderColor,
backgroundColor: '#e2e4e4'
}}>
<div
className='tc fz14 cB fw500'
style={{ minWidth: 70, opacity: e.btnDis ? 0.5 : 1 }}>
{e.btnStr}
</div>
</Button>
</div>
)}
</div>
)
})}
</div>
)
}
// Upcoming
const Upcoming = ({ startTime, commenceTime, uncomingTokens, handleStaking }) => {
const timeStr = dayjs(startTime * 1000)
.utcOffset(60)
.format('HH:mm CET, MMM Do YYYY')
const showPre = dayjs(commenceTime * 1000).isBefore(dayjs())
return (
<div className='p20 radius10' style={{ backgroundColor: '#ededed' }}>
{showPre && (
<Button size='large' color='primary' block onClick={() => handleStaking(uncomingTokens, 1)}>
<div>{I18n.t('staking.preStake')}</div>
</Button>
)}
<div>
<div className='pv15 fw600 fz14'>{I18n.t('staking.airdrops')}</div>
<div className='radius10 bgW p15'>
<div className='flex c row'>
<SvgIcon name='time' size={14} className='cS' />
<div className='fz12 fw500 ml5 cS'>{I18n.t('staking.startAt')}</div>
</div>
<div className='mt10'>
<div className='fz23 fw500'>{timeStr}</div>
</div>
</div>
{uncomingTokens.length > 0 && (
<div className='flex row ac mt15' style={{ flexWrap: 'wrap' }}>
{uncomingTokens.map((d, di) => {
return <StakingTokenItem key={di} className='mr10 mb10' coin={d.token} />
})}
</div>
)}
</div>
</div>
)
}
// Commencing && unstaking
const UnParticipate = ({ statedTokens, unStakeTokens, handleStaking, uncomingTokens }) => {
const uList = uncomingTokens.filter((e) => !statedTokens.find((d) => d.eventId === e.eventId))
return (
<div className='p20 pb10 radius10' style={{ backgroundColor: '#ededed' }}>
<Button size='large' color='primary' block onClick={() => handleStaking([...unStakeTokens, ...uList], 1)}>
<div>{I18n.t('staking.stake')}</div>
</Button>
<div>
<div className='pv15 fw600 fz14'>{I18n.t('staking.airdrops')}</div>
<div className='flex row ac mb10' style={{ flexWrap: 'wrap' }}>
{unStakeTokens.map((d, di) => {
return <StakingTokenItem key={di} className='mr10 mb10' coin={d.token} />
})}
<div className='fz12 cS mb10'>{I18n.t('staking.availableToStake')}</div>
</div>
{uList.length > 0 && (
<div className='flex row ac mb10' style={{ flexWrap: 'wrap' }}>
{uList.map((d, di) => {
return <StakingTokenItem key={di} className='mr10 mb10' coin={d.token} />
})}
<div className='fz12 cS mb10'>{I18n.t('staking.preStake')}</div>
</div>
)}
</div>
</div>
)
}
// Commencing && staked
const Staked = ({ statedTokens, unStakeTokens, uncomingTokens, statedAmount }) => {
const handleStake = (tokens) => {
Base.push('/staking/add', { tokens: JSON.stringify(tokens), amount: statedAmount, type: 4 })
}
const uList = uncomingTokens.filter((e) => !statedTokens.find((d) => d.eventId === e.eventId))
return (
<div className='p20 pb10 radius10' style={{ backgroundColor: '#ededed' }}>
<div className='fw600 fz24 tc'>{I18n.t('staking.title')}</div>
<div>
<div className='pv15 fw600 fz14'>{I18n.t('staking.airdrops')}</div>
<div className='flex row ae jsb mb10' style={{ flexWrap: 'wrap' }}>
<div className='flex flex1 row ac' style={{ flexWrap: 'wrap' }}>
{statedTokens.map((d, di) => {
return <StakingTokenItem className='mr10 mb10' key={di} coin={d.token} />
})}
<div className='fz12 cS mb10'>{I18n.t('staking.title')}</div>
</div>
</div>
{unStakeTokens.length > 0 && (
<div className='flex row ae jsb mb10' style={{ flexWrap: 'wrap' }}>
<div className='flex flex1 row ac' style={{ flexWrap: 'wrap' }}>
{unStakeTokens.map((d, di) => {
return <StakingTokenItem className='mr10 mb10' key={di} coin={d.token} />
})}
<div className='fz12 cS mb10'>{I18n.t('staking.available')}</div>
</div>
<div className='mb5 ml20'>
<Button
style={{ '--border-radius': '20px' }}
color='primary'
size='middle'
onClick={() => handleStake(unStakeTokens)}>
<div className='tc fz14 fw500' style={{ minWidth: 90 }}>
{I18n.t('staking.stake')}
</div>
</Button>
</div>
</div>
)}
{uList.length > 0 && (
<div className='flex row ae jsb mb10' style={{ flexWrap: 'wrap' }}>
<div className='flex flex1 row ac' style={{ flexWrap: 'wrap' }}>
{uList.map((d, di) => {
return <StakingTokenItem key={di} className='mr10 mb10' coin={d.token} />
})}
<div className='fz12 cS mb10'>{I18n.t('staking.soon')}</div>
</div>
<div className='mb5 ml20'>
<Button
style={{ '--border-radius': '20px' }}
onClick={() => handleStake(uList)}
color='primary'
size='middle'>
<div className='tc fz14 fw500' style={{ minWidth: 70 }}>
{I18n.t('staking.preStake')}
</div>
</Button>
</div>
</div>
)}
</div>
</div>
)
}
// Ended
const Ended = ({ statedTokens, unStakeTokens }) => {
return (
<div className='p20 pb10 radius10' style={{ backgroundColor: '#ededed' }}>
<div className='fw600 fz24 tc'>{` `}</div>
<div>
<div className='pv15 fw600 fz14'>{I18n.t('staking.airdrops')}</div>
<div className='flex row ac jsb mb10'>
<div className='flex row ac' style={{ flexWrap: 'wrap' }}>
{[...statedTokens, ...unStakeTokens].map((d, di) => {
return <StakingTokenItem className='mr10 mb10' key={di} coin={d.token} />
})}
</div>
</div>
</div>
</div>
)
}
export const StatusCon = () => {
const [{ filter, rewards }] = useStore('staking.config')
//status: 0->Ended 1->Upcoming ,2->Commencing
const [eventInfo, setEventInfo] = useGetParticipationEvents()
let { status = 0, list = [], upcomingList = [], commencingList = [], endedList = [] } = eventInfo
let [statedTokens] = useStore('staking.statedTokens')
const [statedAmount] = useStore('staking.statedAmount')
const [assetsList] = useStore('common.assetsList')
const assets = assetsList.find((e) => e.name === 'IOTA') || {}
if (statedTokens.length > 0) {
status = 3
}
list = list.filter((e) => !filter.includes(e.id))
const startTime = upcomingList[upcomingList.length - 1]?.startTime
const commenceTime = upcomingList[upcomingList.length - 1]?.commenceTime
useEffect(() => {
let timeHandle = null
if (eventInfo.status === 1) {
timeHandle = setInterval(() => {
if (startTime <= new Date().getTime() / 1000) {
setEventInfo({ ...eventInfo, status: 2 })
}
}, 5000)
}
return () => {
timeHandle && clearInterval(timeHandle)
}
}, [startTime, eventInfo])
const unStakeTokens = []
const uncomingTokens = upcomingList.map((e) => {
const token = e.payload.symbol
let unit = _get(rewards, `${token}.unit`) || token
return {
token: unit,
eventId: e.id,
status: 'uncoming',
limit: e.limit
}
})
statedTokens = statedTokens.map((e) => {
const token = e.token
let unit = _get(rewards, `${token}.unit`) || token
return { ...e, token: unit, status: endedList.find((a) => a.id === e.eventId) ? 'ended' : '' }
})
list.forEach((e) => {
const token = e.payload.symbol
const tokenInfo = statedTokens.find((d) => d.eventId === e.id)
const commencingInfo = commencingList.find((a) => a.id === e.id)
if (!tokenInfo && commencingInfo) {
let unit = _get(rewards, `${token}.unit`) || token
unStakeTokens.push({
token: unit,
eventId: e.id,
status: 'unstake',
limit: e.limit
})
}
})
let available = parseFloat(assets.balance - statedAmount) || 0
if (available < 0) {
available = 0
}
const handleStaking = (tokens, type) => {
if (available < 1) {
return Toast.error(I18n.t('staking.noAvailableTips'))
}
Base.push('/staking/add', { tokens: JSON.stringify(tokens), type })
}
const handleUnstake = () => {
Base.push('/staking/add', { tokens: JSON.stringify(statedTokens), type: 3 })
}
let AirdropsItem = [Ended, Upcoming, UnParticipate, Staked][eventInfo.status || 0]
const unEndedStakeTokens = statedTokens.filter((e) => e.status !== 'ended')
if (unStakeTokens.length === 0 && eventInfo.status == 2 && status == 3) {
AirdropsItem = Staked
}
let amountList = [
{
token: 'IOTA',
amount: available,
statusStr: I18n.t('staking.available'),
borderColor: '#d0d1d2',
btnDis:
eventInfo.status == 0 || unEndedStakeTokens.length == 0 || dayjs(commenceTime * 1000).isAfter(dayjs()) // end
}
]
if (status === 3) {
amountList[0].btnStr = I18n.t('staking.add')
amountList[0].onPress = () => {
handleStaking(unEndedStakeTokens, 2)
}
amountList.push({
token: 'IOTA',
btnDis: statedAmount <= 0,
amount: statedAmount,
statusStr: I18n.t('staking.staked'),
btnStr: I18n.t('staking.unstake'),
onPress: handleUnstake,
borderColor: '#e2e4e4'
})
}
const handleHis = () => {
Base.push('/staking/history')
}
return (
<div className='radius10' style={{ backgroundColor: '#f5f5f5' }}>
<div className='flex row je'>
<div className='flex row ac p15'>
<div className='fz14 mr10'>{I18n.t('staking.his')}</div>
<SvgIcon onClick={handleHis} name='history' className='press' size={20} />
</div>
</div>
<AirdropsItem
uncomingTokens={uncomingTokens}
statedTokens={statedTokens}
handleStaking={handleStaking}
unStakeTokens={unStakeTokens}
startTime={startTime}
statedAmount={statedAmount}
commenceTime={commenceTime}
/>
<AmountCon amountList={amountList} />
</div>
)
}
export const RewardsList = () => {
const [curWallet] = useGetNodeWallet()
const [statedTokens] = useStore('staking.statedTokens')
const stakedRewards = useGetRewards(curWallet)
const [{ rewards }] = useStore('staking.config')
const list = statedTokens.map((e) => {
const { token, eventId } = e
const ratio = _get(rewards, `${token}.ratio`) || 0
let unit = _get(rewards, `${token}.unit`) || token
let total = _get(stakedRewards, `${eventId}.amount`) * ratio || 0
// 1 = 1000m = 1000000u
let preUnit = ''
if (total > 0) {
if (total <= Math.pow(10, -5)) {
total = Math.pow(10, 6) * total
preUnit = 'μ'
} else if (total <= Math.pow(10, -2)) {
total = Math.pow(10, 3) * total
preUnit = 'm'
} else if (total >= Math.pow(10, 4)) {
total = Math.pow(10, -3) * total
preUnit = 'k'
}
}
return {
token,
label: `${Base.formatNum(total)}${preUnit} ${unit}`
}
})
const ListEl = useMemo(() => {
return list.map((e, i) => {
return <StakingTokenItem key={i} className='mr10 mb10' coin={e.token} label={e.label} />
})
}, [JSON.stringify(list)])
if (list.length <= 0) {
return null
}
return (
<div className='mt25'>
<div className='cS fz16'>{I18n.t('staking.estimatedReceived')}</div>
<div className='flex row pv10' style={{ flexWrap: 'wrap' }}>
{ListEl}
</div>
</div>
)
}
export const AirdopsList = () => {
const [{ airdrops }] = useStore('staking.config')
const ListEl = useMemo(() => {
return airdrops.map((e, i) => {
return (
<div
className='press mb10 bgS flex row jsb ac p10'
key={i}
style={{ borderRadius: 8 }}
onClick={() => {
Base.push(e.link, { title: e.token })
}}>
<div className='flex row ac'>
<img className='mr10' style={{ width: 24, height: 24 }} src={Base.getIcon(e.token)} />
<div className='fz12'>{e.desc}</div>
</div>
<SvgIcon name='right' size={14} />
</div>
)
})
}, [JSON.stringify(airdrops)])
if (airdrops.length === 0) {
return null
}
return (
<div className='mt15'>
<div className='cS fz16 mb10'>{I18n.t('staking.airdropsList')}</div>
{ListEl}
</div>
)
}
|
# -*- coding: utf-8 -*-
from xml.etree import ElementTree as ET
#查看文件
# root = ET.XML(open('test.xml','r',encoding='utf-8').read())
# print(root.tag)
#
# for node in root:
# print(node.tag,node.attrib,node.find('rank').text)
#
# print(ET.__file__)
#打开并解析文件内容
tree = ET.parse("test.xml")
root = tree.getroot() #获得根标签
for node in root.iter('year'): #iter 查找元素
new_year = int(node.text) + 1
node.text = str(new_year)
node.set('name','hu') #为当前节点 year 设置属性
node.set('year','26')
del node.attrib['year'] #删除当前节点 year 的属性
tree.write("test.xml") |
/**
* modalEffects.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
var ModalEffects = (function() {
function init() {
var overlay = document.querySelector( '.md-overlay' );
[].slice.call( document.querySelectorAll( '.md-trigger' ) ).forEach( function( el, i ) {
var modal = document.querySelector( '#' + el.getAttribute( 'data-modal' ) ),
close = modal.querySelector( '.md-close' );
function removeModal( hasPerspective ) {
classie.remove( modal, 'md-show' );
if( hasPerspective ) {
classie.remove( document.documentElement, 'md-perspective' );
}
}
function removeModalHandler() {
removeModal( classie.has( el, 'md-setperspective' ) );
}
el.addEventListener( 'click', function( ev ) {
document.getElementsByTagName('body')[0].style.overflow = 'hidden';
classie.add( modal, 'md-show' );
overlay.removeEventListener( 'click', removeModalHandler );
overlay.addEventListener( 'click', removeModalHandler );
if( classie.has( el, 'md-setperspective' ) ) {
setTimeout( function() {
classie.add( document.documentElement, 'md-perspective' );
}, 25 );
}
});
close.addEventListener( 'click', function( ev ) {
document.getElementsByTagName('body')[0].style.overflow = 'scroll';
ev.stopPropagation();
removeModalHandler();
});
} );
}
init();
})(); |
import {Octokit} from "@octokit/rest"
import {Image, Link} from "blitz"
import {useEffect, useState} from "react"
import {ButtonLink} from "@/components/ButtonLink"
import {Header} from "@/components/Header"
import {Feature} from "@/components/home/Feature"
import {FeatureIcon} from "@/components/home/FeatureIcon"
import {FeatureIconTitle} from "@/components/home/FeatureIconTitle"
import {Footer} from "@/components/home/Footer"
import {Hand} from "@/components/home/Hand"
import {HeroCode} from "@/components/home/HeroCode"
import {StyledLink} from "@/components/home/StyledLink"
import {VideoPlayer} from "@/components/home/VideoPlayer"
import Scrollbar from "@/components/Scrollbar"
import {SocialCards} from "@/components/SocialCards"
import {SponsorPack} from "@/components/SponsorPack"
import {getGitHubFile} from "@/utils/getGitHubFile"
const Home = ({randomContributors}) => {
const [navIsOpen, setNavIsOpen] = useState(false)
useEffect(() => {
document.body.style.overflow = navIsOpen ? "hidden" : "unset"
}, [navIsOpen])
return (
<div>
<SocialCards imageUrl="/social-homepage.png" />
<div className="overflow-hidden">
<div>
<a name="top" aria-hidden>
{null}
</a>
<div className="relative grid grid-cols-1 py-1 md:py-3 gap-y-24 xl:gap-y-44">
<div className="z-30 text-white col-span-full">
<Header
className="px-6 mx-auto max-w-7xl"
onNavToggle={(isOpen) => {
setNavIsOpen(isOpen)
}}
/>
</div>
<div
className={
"absolute w-full h-full row-start-1 row-end-5 background-to-video rounded-bl-3xl xl:rounded-bl-4xl bg-gradient-to-b from-purple-mid to-purple-primary dark:from-black dark:to-purple-off-black " +
(navIsOpen ? "z-20 fixed" : "-z-10")
}
></div>
<div className="relative -mt-6 text-white col-span-full">
<div className="grid grid-cols-1 gap-10 px-6 mx-auto max-w-7xl lg:grid-cols-3 xl:grid-cols-2 md:gap-6 xl:-mt-10">
<div className="z-10 space-y-10 lg:w-full">
<h2 className="-mt-8 font-medium text-5xl-squashed lg:-mt-0 font-secondary xl:text-6xl xl:font-medium dark:text-transparent bg-clip-text bg-gradient-to-r from-blue-gradient-white to-blue-gradient-light-blue">
El Framework FullStack de React
</h2>
<p className="text-lg xl:text-xl xl:font-medium text-off-white lg:text-transparent lg:bg-clip-text lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue xl:w-4/5">
Blitz es un framework todo en uno y listo para su uso, que está inspirado en
Ruby on Rails, construido sobre Next.js y que cuenta con las características de
la capa de datos "Zero-API" que elimina la necesidad de usar REST/GraphQL.
</p>
<div className="flex space-x-4">
<ButtonLink className="w-2/3 lg:w-auto rounded-tl-xl" href="/docs/get-started">
Prueba Blitz en menos de 5 minutos
</ButtonLink>
<ButtonLink
href="https://github.com/blitz-js/blitz"
target="_blank"
rel="noopener noreferrer"
variant="outline"
className="w-1/3 lg:w-auto rounded-r-xl"
>
Github
</ButtonLink>
</div>
</div>
<div className="relative lg:col-span-2 xl:col-span-1">
<Hand variant="hero-squiggle" className="lg:hidden -right-6 -top-36" />
<Hand variant="hero-rightarm" className="hidden lg:block -left-36 top-32" />
<Hand
variant="hero-righthand"
className="z-20 hidden lg:block -left-4"
style={{top: "15.2rem"}}
/>
<Hand
variant="hero-leftarm"
className="hidden lg:block"
style={{top: "30rem", right: "-4.8rem"}}
/>
<Hand
variant="hero-lefthand"
style={{top: "26.6rem", right: "-2.2em"}}
className="z-20 hidden lg:block"
/>
<HeroCode className="z-10" />
</div>
</div>
</div>
<div className="z-10 px-6 mx-auto space-y-12 text-lg text-center text-white lg:space-y-0 lg:space-x-12 lg:flex lg:text-left max-w-7xl xl:font-mediumxl:text-xl">
<FeatureIcon icon="layers">
“Zero-API” te permite{" "}
<strong>importar el código del servidor directamente a tus componentes</strong> en
lugar de tener que crear cada ruta API, realizar las peticiones desde el cliente y
manejar el caché.
</FeatureIcon>
<FeatureIcon icon="lighteningBolt">
¡Las nuevas aplicaciones Blitz vienen con{" "}
<strong>todas las cosas aburridas previamente configuradas!</strong> Como ESLint,
Prettier, Jest, registro de usuario, inicio de sesión y restablecimiento de
contraseña.
</FeatureIcon>
<FeatureIcon icon="graphUp">
Proporciona <strong>convenciones y valores predeterminados útiles</strong> para
cosas como enrutamiento, estructura de archivos y autentificación, además de ser
extremadamente flexible.
</FeatureIcon>
</div>
<div className="grid w-full gap-5 px-6 mx-auto text-white xl:gap-10 max-w-7xl lg:grid-cols-2">
<Link href="/#" passHref>
<StyledLink className="flex items-center justify-between pb-1 text-lg border-b border-opacity-50 border-blue-mid lg:col-span-2 font-secondary xl:text-xl">
<span>Vídeos destacados</span>
{/*
<span className="flex items-center">
<span className="hidden mr-2 lg:block">View News</span>{" "}
<BsArrowRight size="1.5rem" />
</span>
*/}
</StyledLink>
</Link>
<VideoPlayer url="https://www.youtube.com/watch?v=UHyx8MtCVVk" />
<VideoPlayer url="https://www.youtube.com/watch?v=fIexr5UZfhU" />
</div>
<div className="relative w-full mx-auto space-y-10 lg:space-y-20 xl:space-y-36 max-w-7xl">
<h2 className="px-6 text-3xl font-semibold xl:text-5xl xl:w-1/2">
Todo lo que necesitas para tus aplicaciones en producción
</h2>
<div className="w-full">
<Hand
variant="concepts-right"
className="hidden lg:block lg:-top-24 lg:-right-96 lg:w-8/12 xl:-top-14"
/>
<Scrollbar className="lg:hidden" thumbHeight="4px">
<div className="grid pb-4 ml-6 features-grid lg:gap-y-14">
<Feature title="Fullstack & Monolítico">
<p>
Incluye todo, desde la base de datos hasta su interfaz, todo dentro de una
sola aplicación. Sólo un proyecto para desarrollo, sólo un proyecto para
desplegar a producción.
</p>
<p>Y puedes publicar tu proyecto en tu servidor o serverless.</p>
</Feature>
<Feature title="Sin necesidad de API">
<p>
En lugar de obtener los datos del backend, importa el código de tu servidor
directamente en tus componentes. En el momento de la compilación, esta
función importa e intercambia los datos con una API HTTP generada
automáticamente.
</p>
<p>
La API generada también puede ser utilizada por otras aplicaciones y por
terceros.
</p>
</Feature>
<Feature title="Opiniones sueltas">
<p>
Esta novedosa experiencia te guía por un camino perfecto para la mayoría de
las aplicaciones. Pero cuando necesitas salir de los caminos marcados, eres
totalmente libre de hacerlo.
</p>
<p>
Y casi todo se puede hacer con un plugin. Por ejemplo, no exigimos qué
estilos o bibliotecas de formularios utilizar.
</p>
</Feature>
<Feature title="Convención sobre configuración">
<p>
Blitz realiza todas las tareas aburridas de configuración y montaje por ti.
La estructura común del proyecto y los patrones arquitectóncos hacen que sea
más fácil pasar de una aplicación Blitz a otra y sentirse inmediatamente
como en casa.
</p>
</Feature>
<Feature title="Fácil de comenzar, fácil de escalar">
<p>
Fácil para principiantes y fácil de migrar aplicaciones ya existentes de
Next.js a Blitz.
</p>
<p>
Fácil de escalar en todas las formas: líneas de código, número de personas
que trabajan en la base el código y ejecución del código.
</p>
</Feature>
<Feature title="Estabilidad">
<p>
Una vez que alcancemos la versión 1.0, cambiaremos a un ciclo de lanzamiento
estable y predecible con múltiples canales como stable, LTS y beta.
</p>
<p>Nos estamos inspirando mucho en Ember en este aspecto.</p>
</Feature>
</div>
</Scrollbar>
</div>
</div>
<div className="absolute w-full h-full row-start-6 lg:h-codesandbox lg:mt-80 row-end-10 rounded-bl-3xl rounded-tr-3xl lg:rounded-bl-4xl lg:rounded-tr-4xl bg-gradient-to-b from-purple-mid to-purple-primary dark:from-purple-off-black dark:to-black"></div>
<div className="relative hidden w-full px-6 mx-auto space-y-10 max-w-7xl lg:block">
<h3 className="pb-1 text-xs border-b border-opacity-50 font-secondary border-blue-mid">
Blitz CodeSandbox Example
</h3>
<div>
<Hand variant="sandbox-right" style={{right: "-13.2rem", bottom: "-35rem"}} />
<a
target="_blank"
rel="noopener noreferrer"
href="https://codesandbox.io/s/flamboyant-meninsky-j63yq?file=/app/projects/mutations/createProject.ts"
className="h-sandbox xl:h-xl-sandbox block relative"
>
<Image src="/img/sandbox-pic.png" layout="fill" className="object-cover" />
<div className="absolute inset-0 bg-gray-800 opacity-0 hover:opacity-70 flex items-center justify-center text-white text-6xl font-bold">
Click to Open in New Tab
</div>
</a>
</div>
</div>
<div className="xl:hidden">{/*spacer div*/}</div>
<div className="relative flex flex-col px-6 mx-auto text-white lg:flex-row max-w-7xl space-y-14 lg:space-x-24 lg:space-y-0 xl:space-x-40">
<div className="space-y-14 lg:w-1/2">
<h2 className="z-10 font-medium text-transparent text-5xl-squashed font-secondary bg-clip-text bg-gradient-to-r from-blue-gradient-white to-blue-gradient-light-blue xl:text-6xl">
La comunidad de Blitz: nuestro aspecto más importante
</h2>
<div className="z-10 grid grid-cols-5 gap-1 md:grid-cols-6 lg:grid-cols-5 grid-rows-8 overflow-clip">
{randomContributors.map((contributor, i) => (
<a
href={`https://github.com/${contributor.login}`}
key={i}
target="_blank"
rel="noopener noreferrer"
>
<img
src={contributor.avatar_url}
alt={contributor.name}
title={contributor.name}
className="w-full"
/>
</a>
))}
</div>
</div>
<div className="grid grid-cols-1 text-lg lg:relative gap-14 md:grid-cols-2 lg:row-span-2 lg:grid-cols-1 xl:text-xl lg:w-1/2">
<Hand variant="community-squiggle" className="xl:hidden -right-18" />
<div className="z-10 flex flex-col justify-between space-y-6 lg:justify-end">
<div className="flex flex-col space-y-6 lg:h-auto lg:text-transparent text-off-white">
<p className="lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue lg:bg-clip-text">
¡Nuestra comunidad es cálida, segura, diversa, inclusiva y divertida! LGBTQ+,
mujeres y minorías son especialmente bienvenidos.
</p>
<p className="lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue lg:bg-clip-text">
Por favor lee nuestro{" "}
<Link href="/docs/code-of-conduct" passHref>
<StyledLink className="underline text-off-white hover:text-blue-light">
Código de Conducta
</StyledLink>
</Link>
.
</p>
</div>
<ButtonLink
href="https://discord.blitzjs.com/"
target="_blank"
rel="noopener noreferrer"
className="rounded-bl-none rounded-xl lg:w-max"
>
Únete a nuestra comunidad de Discord
</ButtonLink>
</div>
<div className="z-10 flex flex-col justify-between space-y-6 lg:justify-start">
<div className="flex flex-col space-y-6 lg:h-auto lg:text-transparent text-off-white lg:bg-clip-text lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue">
<p className="lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue lg:bg-clip-text">
Estamos todos juntos en esto, desde los más jóvenes hasta los más mayores.
Tenemos más cosas en común que las que nos diferencian. Nos encanta trabajar
juntos.
</p>
<p className="lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue lg:bg-clip-text">
¡Te invitamos a ayudar a que Blitz sea el mejor framework que hemos tenido!
</p>
</div>
<Link href="/docs/contributing" passHref>
<ButtonLink className="rounded-bl-none rounded-xl lg:w-max">
Aprende a contribuir
</ButtonLink>
</Link>
</div>
</div>
</div>
<div className="z-10 w-full mx-auto text-white space-y-7 max-w-7xl">
<h2 className="px-6 text-2xl font-medium text-white font-secondary lg:text-3xl">
Diagrama de la arquitectura
</h2>
<div className="w-full">
<Scrollbar className="lg:hidden" thumbHeight="4px" thumbColor="white">
<div className="px-6 architecture-diagram" style={{ paddingBottom: "2px" }}>
<img src="img/architecture.svg" alt="Diagrama de la Arquitectura" />
</div>
</Scrollbar>
</div>
</div>
<div className="relative col-span-full">
<Hand variant="features-squiggle" className="-right-6 -top-10 xl:hidden -z-10" />
</div>
<div className="absolute w-full h-full row-start-8 row-end-19 xl:row-end-19 -z-20 bg-purple-mid dark:bg-purple-off-black"></div>
<div className="relative px-6 mx-auto my-6 space-y-12 text-white xl:my-0 max-w-7xl xl:space-y-36">
<h2 className="text-3xl font-semibold lg:text-transparent lg:bg-clip-text lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue xl:text-5xl">
End-to-End, <br className="hidden xl:block" />
desde la base de datos hasta el navegador
</h2>
<div className="grid gap-12 md:grid-cols-2 xl:grid-cols-3">
<Hand
variant="features-right"
className="hidden xl:block xl:-top-40 xl:-right-52"
/>
<FeatureIconTitle icon="thumbsUp" title="Autenticación y Autorización">
La autenticación integrada es muy fácil y muy segura. Funciona con cualquier
proveedor de identidad, incluidos el nombre de usuario y contraseña de tu hosting
y terceros como Auth0.
</FeatureIconTitle>
<FeatureIconTitle icon="database" title="Cualquier base de datos">
Puedes utilizar la base de datos que quieras. Prisma 2 es el cliente de base de
datos predeterminado, pero puedes eliminarlo y usar cualquier otro como Fauna o
DynamoDB.
</FeatureIconTitle>
<FeatureIconTitle icon="fileCode" title="Recetas">
Un comando para instalar el código y/o paquetes de tu aplicación blitz. Ejemplos:
`blitz install tailwind` o `blitz install chakra-ui`. Cualquiera puede crear una
"receta".
</FeatureIconTitle>
<FeatureIconTitle icon="plugin" title="Arquitectura Backend">
Blitz está configurado para tareas que requieren un uso intensivo del servidor,
como enviar emails, cronjobs, procesamiento en segundo plano, generar archivos
PDF, etc. Actualmente tenemos pocas guías de backend, pero estamos trabajando para
desarrollar más patrones y agregar más documentos.
</FeatureIconTitle>
<FeatureIconTitle
icon="typescript"
title="Soporte para TypeScript de primera clase"
>
Blitz está construido con TypeScript y la capa de datos de Blitz está
completamente asegurada por tipos. ¡Todos los tipos son completamente estáticos
sin necesidad de un proceso de generación por separado!
</FeatureIconTitle>
<FeatureIconTitle icon="scaffolding" title="Código Scaffolding">
Es pronto, pero el código de Blitz será extremadamente poderoso, ideal tanto para
la creación de prototipos como para la creación de aplicaciones reales. Podrás
modificar cualquier plantilla y personalizarla para tu proyecto.
</FeatureIconTitle>
</div>
</div>
<div className="absolute w-full h-full bg-white dark:bg-black row-start-11 row-end-13 rounded-tr-3xl xl:rounded-tr-4xl -z-10" />
<div className="relative col-span-full">
<Hand
variant="sponsors-squiggle"
className="-right-24 xl:hidden"
style={{top: "-5.3rem"}}
/>
</div>
<div className="px-6 mx-auto text-center max-w-7xl ">
<div className="space-y-7 xl:space-y-10">
<h2 className="relative text-3xl font-semibold xl:text-5xl">
<Hand
variant="sponsors-left"
className="hidden xl:block -left-80 pointer-events-none"
style={{top: "-18.05rem"}}
/>
Nuestros Patrocinadores
</h2>
<p className="text-lg xl:text-xl">
¡Tus contribuciones financieras ayudan a garantizar que Blitz continúe
desarrollándose y <br className="hidden lg:block" />
manteniéndose!. Tenemos opciones de patrocinio mensual a partir de $5/mes.
</p>
<div>
<ButtonLink
variant="solid-dark"
href="https://github.com/sponsors/blitz-js"
className="mx-auto rounded-bl-none rounded-xl lg:w-max md:w-1/3 lg:m-auto lg:mt-4 xl:mt-18"
target="_blank"
rel="noopener noreferrer"
>
Apoya a Blitz
</ButtonLink>
</div>
</div>
<div className="xl:max-w-2xl mx-auto">
<SponsorPack />
</div>
</div>
<div className="w-full px-6 mx-auto space-y-12 text-white lg:space-x-4 lg:space-y-0 lg:flex lg:items-center max-w-7xl">
<h2 className="pr-2 text-3xl font-semibold lg:w-full lg:text-transparent lg:bg-clip-text lg:bg-gradient-to-r lg:from-blue-gradient-white lg:to-blue-gradient-light-blue xl:text-5xl">
¿Qué debería hacer ahora?
</h2>
<div className="flex flex-col w-full space-y-4 md:flex-row md:space-y-0 md:space-x-2">
<ButtonLink
href="/docs/get-started"
className="w-full text-lg py-18 rounded-t-2xl md:rounded-tr-none"
>
Prueba Blitz en menos de 5 minutos
</ButtonLink>
<ButtonLink
target="_blank"
rel="noopener noreferrer"
href="https://discord.blitzjs.com"
className="w-full text-lg py-18 rounded-br-2xl md:rounded-tr-2xl"
>
Únete a Discord
</ButtonLink>
</div>
</div>
<Footer className="dark:bg-purple-off-black bg-purple-mid text-white" />
</div>
</div>
</div>
</div>
)
}
const getStaticProps = async () => {
const MAX_CONTRIBUTORS = 30
const octokit = new Octokit({
auth: process.env.GITHUB_AUTH_TOKEN,
})
const {contributors} = await getGitHubFile({
octokit,
owner: "blitz-js",
repo: "blitz",
path: ".all-contributorsrc",
json: true,
})
let randomIndexes = []
while (randomIndexes.length < MAX_CONTRIBUTORS) {
var r = Math.floor(Math.random() * contributors.length)
if (randomIndexes.indexOf(r) === -1) randomIndexes.push(r)
}
let randomContributors = randomIndexes.map((i) => contributors[i])
return {
props: {randomContributors},
revalidate: 60 * 30, // 30 minutes
}
}
Home.layoutProps = {
meta: {
title: "Blitz.js - El Framework FullStack de React",
description: `Blitz es un framework fullstack de React hiperproductivo construido sobre Next.js y cuenta con la capa de datos "Zero-API".`,
},
}
export default Home
export {getStaticProps}
|
const qs = require("querystring");
const id = "vue-loader-plugin";
const NS = "vue-loader";
const BasicEffectRulePlugin = require("webpack/lib/rules/BasicEffectRulePlugin");
const BasicMatcherRulePlugin = require("webpack/lib/rules/BasicMatcherRulePlugin");
const DescriptionDataMatcherRulePlugin = require("webpack/lib/rules/DescriptionDataMatcherRulePlugin");
const RuleSetCompiler = require("webpack/lib/rules/RuleSetCompiler");
const UseEffectRulePlugin = require("webpack/lib/rules/UseEffectRulePlugin");
const ruleSetCompiler = new RuleSetCompiler([
new BasicMatcherRulePlugin("test", "resource"),
new BasicMatcherRulePlugin("mimetype"),
new BasicMatcherRulePlugin("dependency"),
new BasicMatcherRulePlugin("include", "resource"),
new BasicMatcherRulePlugin("exclude", "resource", true),
new BasicMatcherRulePlugin("conditions"),
new BasicMatcherRulePlugin("resource"),
new BasicMatcherRulePlugin("resourceQuery"),
new BasicMatcherRulePlugin("resourceFragment"),
new BasicMatcherRulePlugin("realResource"),
new BasicMatcherRulePlugin("issuer"),
new BasicMatcherRulePlugin("compiler"),
new DescriptionDataMatcherRulePlugin(),
new BasicEffectRulePlugin("type"),
new BasicEffectRulePlugin("sideEffects"),
new BasicEffectRulePlugin("parser"),
new BasicEffectRulePlugin("resolve"),
new BasicEffectRulePlugin("generator"),
new UseEffectRulePlugin(),
]);
class VueLoaderPlugin {
apply(compiler) {
const webpack = compiler.webpack.NormalModule || require("webpack/lib/NormalModule");
// add NS marker so that the loader can detect and report missing plugin
compiler.hooks.compilation.tap(id, (compilation) => {
const normalModuleLoader = webpack.getCompilationHooks(compilation).loader;
normalModuleLoader.tap(id, (loaderContext) => {
loaderContext[NS] = true;
});
});
const rules = compiler.options.module.rules;
let rawVueRules;
let vueRules = [];
for (const rawRule of rules) {
// skip rules with 'enforce'. eg. rule for eslint-loader
if (rawRule.enforce) {
continue;
}
// skip the `include` check when locating the vue rule
const clonedRawRule = Object.assign({}, rawRule);
delete clonedRawRule.include;
const ruleSet = ruleSetCompiler.compile([
{
rules: [clonedRawRule],
},
]);
vueRules = ruleSet.exec({
resource: "foo.vue",
});
if (!vueRules.length) {
vueRules = ruleSet.exec({
resource: "foo.vue.html",
});
}
if (vueRules.length > 0) {
if (rawRule.oneOf) {
throw new Error(
`[VueLoaderPlugin Error] vue-loader 15 currently does not support vue rules with oneOf.`
);
}
rawVueRules = rawRule;
break;
}
}
if (!vueRules.length) {
throw new Error(
`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +
`Make sure there is at least one root-level rule that matches .vue or .vue.html files.`
);
}
// get the normlized "use" for vue files
const vueUse = vueRules.filter((rule) => rule.type === "use").map((rule) => rule.value);
// get vue-loader options
const vueLoaderUseIndex = vueUse.findIndex((u) => {
return /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader);
});
if (vueLoaderUseIndex < 0) {
throw new Error(
`[VueLoaderPlugin Error] No matching use for vue-loader is found.\n` +
`Make sure the rule matching .vue files include vue-loader in its use.`
);
}
// make sure vue-loader options has a known ident so that we can share
// options by reference in the template-loader by using a ref query like
// template-loader??vue-loader-options
const vueLoaderUse = vueUse[vueLoaderUseIndex];
vueLoaderUse.ident = "vue-loader-options";
vueLoaderUse.options = vueLoaderUse.options || {};
// for each user rule (expect the vue rule), create a cloned rule
// that targets the corresponding language blocks in *.vue files.
const refs = new Map();
const clonedRules = rules
.filter((r) => r !== rawVueRules)
.map((rawRule) => cloneRule(rawRule, refs));
// fix conflict with config.loader and config.options when using config.use
delete rawVueRules.loader;
delete rawVueRules.options;
rawVueRules.use = vueUse;
// global pitcher (responsible for injecting template compiler loader & CSS
// post loader)
const pitcher = {
loader: require.resolve("./loaders/pitcher"),
resourceQuery: (query) => {
if (!query) {
return false;
}
const parsed = qs.parse(query.slice(1));
return parsed.vue != null;
},
options: {
cacheDirectory: vueLoaderUse.options.cacheDirectory,
cacheIdentifier: vueLoaderUse.options.cacheIdentifier,
},
};
// replace original rules
compiler.options.module.rules = [pitcher, ...clonedRules, ...rules];
}
}
let uid = 0;
function cloneRule(rawRule, refs) {
const rules = ruleSetCompiler.compileRules(
`clonedRuleSet-${++uid}`,
[
{
rules: [rawRule],
},
],
refs
);
let currentResource;
const conditions = rules[0].rules
.map((rule) => rule.conditions)
// shallow flat
.reduce((prev, next) => prev.concat(next), []);
// do not process rule with enforce
if (!rawRule.enforce) {
const ruleUse = rules[0].rules
.map((rule) =>
rule.effects.filter((effect) => effect.type === "use").map((effect) => effect.value)
)
// shallow flat
.reduce((prev, next) => prev.concat(next), []);
// fix conflict with config.loader and config.options when using config.use
delete rawRule.loader;
delete rawRule.options;
rawRule.use = ruleUse;
}
const res = Object.assign({}, rawRule, {
resource: (resources) => {
currentResource = resources;
return true;
},
resourceQuery: (query) => {
if (!query) {
return false;
}
const parsed = qs.parse(query.slice(1));
if (parsed.vue == null) {
return false;
}
if (!conditions) {
return false;
}
const fakeResourcePath = `${currentResource}.${parsed.lang}`;
for (const condition of conditions) {
// add support for resourceQuery
const request = condition.property === "resourceQuery" ? query : fakeResourcePath;
if (condition && !condition.fn(request)) {
return false;
}
}
return true;
},
});
delete res.test;
if (rawRule.rules) {
res.rules = rawRule.rules.map((rule) => cloneRule(rule, refs));
}
if (rawRule.oneOf) {
res.oneOf = rawRule.oneOf.map((rule) => cloneRule(rule, refs));
}
return res;
}
VueLoaderPlugin.NS = NS;
module.exports = VueLoaderPlugin;
|
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..proxima.simple_index import build_index, search_index
METRIC_TO_PROXIMA_METRIC_TYPE = {
'l2': 'Euclidean',
'euclidean': 'Euclidean',
'canberra': 'Canberra',
'chebyshev': 'Chebyshev',
'sqeuclidean': 'SquaredEuclidean',
'innerproduct': 'InnerProduct',
'manhattan': 'Manhattan'
}
build_proxima_index = build_index
proxima_query = search_index
|
import typeScriptPlugin from 'rollup-plugin-typescript2';
import path from 'path';
import { terser } from 'rollup-plugin-terser';
const pkg = require(path.resolve(__dirname, `package.json`));
const banner = `/*!
* ${pkg.name} v${pkg.version}
* (c) ${new Date().getFullYear()} ${pkg.author.name}
* @license MIT
*/`;
const createformat = (config) => {
const defaultConfig = Object.assign({ output: {}, plugins: [] }, config);
return {
input: './src/index.ts',
plugins: [
typeScriptPlugin({
check: false,
tsconfig: path.resolve(__dirname, './tsconfig.json'),
tsconfigOverride: {
exclude: ['./src/__tests__/**/*.ts', './src/jest/**/*.ts']
}
}),
...defaultConfig.plugins
],
external: ['vue'],
output: defaultConfig.output
};
};
export default [
createformat({
output: {
banner,
file: `./dist/${pkg.name}.esm-browser.js`,
format: 'es'
}
}),
createformat({
output: {
banner,
file: `./dist/${pkg.name}.prod.js`,
format: 'cjs'
},
plugins: [
terser({
compress: {
ecma: 2015
}
})
]
})
];
|
from beet import Context, Function
def beet_default(ctx: Context):
function_path = ctx.cache.generated.directory / "foo.mcfunction"
if not function_path.is_file():
function_path.write_text("say hello\n")
ctx.data["demo:foo"] = Function(source_path=function_path)
|
export default {
setEmployees : (state,emps) => state.employees = emps,
newEmployee : (state,emp) => state.employees.push(emp),
setDialogStatus : (state,status) => state.addDialog = status,
setLogginStatus : (state,loginStatus) => state.loggedin = loginStatus,
setResponse : (state,resp) => state.response = resp,
} |
import UsersSerializer from '../users';
class AdminUsersSerializer extends UsersSerializer {
}
export default AdminUsersSerializer;
|
import React, { PropTypes } from 'react';
import { DISPLAY_NAME_PREFIX } from '../../constants';
import BaseCollectionHelper from '../BaseCollectionHelper';
const Reverse = ({ collection, ...baseProps }) => (
<BaseCollectionHelper
collection={collection.slice().reverse()}
{...baseProps}
/>
);
Reverse.displayName = `${DISPLAY_NAME_PREFIX}Reverse`;
Reverse.propTypes = {
collection: PropTypes.array,
};
export default Reverse;
|
let ifSettingsPasswordUpdated = document.querySelector("#ifSettingsPasswordUpdated");
let settingsUpdateButton = document.querySelector("#settingsUpdateButton");
let settingsPasswordChangeInput1 = document.querySelector("#settingsPasswordChangeInput1")
let settingsPasswordChangeInput2 = document.querySelector("#settingsPasswordChangeInput2")
let settingsPasswordChangeInput3 = document.querySelector("#settingsPasswordChangeInput3")
settingsUpdateButton.addEventListener("click",()=>{
if(!settingsPasswordChangeInput1.value){
settingsPasswordChangeInput1.style.borderColor = 'red';
}else if(!settingsPasswordChangeInput2.value){
settingsPasswordChangeInput2.style.borderColor = 'red';
}else if(!settingsPasswordChangeInput3.value){
settingsPasswordChangeInput3.style.borderColor = 'red';
}else{
settingsPasswordChangeInput1.style.borderColor = '#303030'
settingsPasswordChangeInput2.style.borderColor = '#303030'
settingsPasswordChangeInput3.style.borderColor = '#303030'
settingsPasswordChangeInput1.value = ''
settingsPasswordChangeInput2.value = ''
settingsPasswordChangeInput3.value = ''
ifSettingsPasswordUpdated.style.visibility = 'visible'
setTimeout(()=>{
ifSettingsPasswordUpdated.style.visibility = 'hidden'
},1500)
}
})
|
webpackHotUpdate("cms",{
/***/ "./node_modules/css-loader/index.js?!./node_modules/gatsby-plugin-postcss/node_modules/postcss-loader/src/index.js?!./src/components/Footer.css":
/*!************************************************************************************************************************************************************************!*\
!*** ./node_modules/css-loader??ref--12-oneOf-1-1!./node_modules/gatsby-plugin-postcss/node_modules/postcss-loader/src??ref--12-oneOf-1-2!./src/components/Footer.css ***!
\************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var escape = __webpack_require__(/*! ../../node_modules/css-loader/lib/url/escape.js */ "./node_modules/css-loader/lib/url/escape.js");
exports = module.exports = __webpack_require__(/*! ../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(true);
// imports
// module
exports.push([module.i, "*{\r\n margin:0px;\r\n padding: 0px;\r\n -webkit-box-sizing: border-box;\r\n box-sizing: border-box;\r\n}\r\nbody{\r\n font-family: 'Open Sans', sans-serif;\r\n}\r\n.clr{\r\n clear: both;\r\n}\r\n.footer-wrapper{\r\n width: 100%;\r\n height: auto;\r\n min-height: 250px;\r\n margin:auto;\r\n background-image: url(" + escape(__webpack_require__(/*! ../../static/images/footer-bg.jpg */ "./static/images/footer-bg.jpg")) + ");\r\n background-position: center;\r\n background-repeat: no-repeat;\r\n background-attachment: fixed;\r\n background-size: cover;\r\n overflow: hidden;\r\n position: absolute;\r\n padding-top: 75px;\r\n bottom: 0px;\r\n}\r\n\r\n.footer-mid-part{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n}\r\n.footer-section-one{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n padding: 20px 20px;\r\n background: rgba(255,255,255,.1);\r\n}\r\n.footer-section-two{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n padding: 20px 20px;\r\n}\r\n.footer-section-three{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n padding: 20px 20px;\r\n background: rgba(255,255,255,.1);\r\n}\r\n.footer-heading{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n}\r\n.footer-heading h2{\r\n font-size: 18px;\r\n text-align: left;\r\n color: #fff;\r\n text-transform: uppercase;\r\n margin: 0px;\r\n}\r\n.footer-contact-box{\r\n width: 100%;\r\n height: auto;;\r\n margin: auto;\r\n margin-top: 13px;\r\n}\r\n.footer-contact-icon{\r\n width: 25px;\r\n height: 25px;\r\n float: left;\r\n}\r\n.footer-contact-icon i{\r\n color: #fff;\r\n font-size: 20px;\r\n}\r\n.footer-contact-text{\r\n width: 85%;\r\n height: auto;\r\n float: left;\r\n margin-left: 10px;\r\n}\r\n.footer-contact-text p{\r\n font-size: 14px;\r\n text-align: left;\r\n color: #fff;\r\n cursor: pointer;\r\n}\r\n.footer-contact-text p a{\r\n font-size: 14px;\r\n text-align: left;\r\n color: #fff;\r\n text-decoration: none;\r\n\r\n}\r\n.footer-contact-text p:hover{\r\n color: #f00;\r\n}\r\n.footer-contact-box:hover .footer-contact-icon i{\r\n color: #f00;\r\n}\r\n.footer-contact-box:hover .footer-contact-text p a{\r\n color: #f00;\r\n}\r\n.footer-link{\r\n width: 100%;\r\n height:auto;\r\n margin: auto;\r\n margin-top: 20px;\r\n}\r\n.footer-link ul{\r\n margin:0px;\r\n padding: 0px;\r\n}\r\n.footer-link ul li{\r\n list-style-type: none;\r\n text-align: center;\r\n padding-top: 5px;\r\n}\r\n.footer-link ul li a{\r\n font-size: 14px;\r\n color: #fff;\r\n text-decoration: none;\r\n text-transform: capitalize;;\r\n}\r\n.footer-link ul li a:hover{\r\n color: #f00;\r\n}\r\n.footer-section-two .footer-heading h2{\r\n text-align: center;\r\n}\r\n.footer-form{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n margin-top: 20px;\r\n}\r\n.footer-form-box{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n margin-top: 20px;\r\n}\r\n.footer-form-style{\r\n width: 100%;\r\n height: 40px;\r\n border-left: none;\r\n border-top: none;\r\n border-right: none;\r\n border-bottom:1px solid rgba(255,255,255,.1);\r\n background:transparent;\r\n font-size: 14px;\r\n text-align: left;\r\n padding: 0px 10px;\r\n color: #fff;\r\n}\r\n.footer-form-submit-style{\r\n width: 129px;\r\n height: 35px;\r\n font-size: 16px;\r\n text-align: center;\r\n color: #fff;\r\n text-transform: uppercase;\r\n background: rgba(255,255,255,.5);\r\n border:none;\r\n margin-top: 1px;\r\n}\r\n.footer-form-submit-style:active{\r\n background: #f00;\r\n}\r\n.footer-bottom{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n margin-top: 10px;\r\n margin-bottom: 10px;\r\n}\r\n.footer-bottom{\r\n font-size: 14px;\r\n text-align: center;\r\n color: #fff;\r\n}\r\n.top-img{\r\n position: absolute;\r\n background: url(" + escape(__webpack_require__(/*! ../../static/images/top-divder.png */ "./static/images/top-divder.png")) + ");\r\n top: -20px;\r\n left: 0px;\r\n width: 100%;\r\n height: 55px;\r\n}\r\nh1{\r\n font-size: 60px;\r\n text-align: center;\r\n text-transform: uppercase;\r\n padding-top: 30px;\r\n}\r\nh1 span{\r\n color: #f00;\r\n}\r\n/*RESPONSIVE CODE*/\r\n@media only screen and (max-width: 1199px){\r\n .footer-wrapper{\r\n \r\n width: 100%;\r\n height: auto;\r\n min-height: 250px;\r\n margin:auto;\r\n background-image: url(" + escape(__webpack_require__(/*! ../../static/images/footer-bg.jpg */ "./static/images/footer-bg.jpg")) + ");\r\n background-position: center;\r\n background-repeat: no-repeat;\r\n background-attachment: fixed;\r\n background-size: cover;\r\n overflow: hidden;\r\n position: absolute;\r\n padding-top: 75px;\r\n bottom: 0px;\r\n }\r\n h1{\r\n font-size: 4vw!important;\r\n padding-top: 10px;\r\n padding-bottom: 10px;\r\n }\r\n .footer-section-one{\r\n padding: 12px;\r\n }\r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n", "", {"version":3,"sources":["D:/gatsby/Vertex/gatsby-website/src/components/D:/gatsby/Vertex/gatsby-website/src/components/Footer.css"],"names":[],"mappings":"AAAA;EACE,WAAU;EACV,aAAY;EACZ,+BAAsB;UAAtB,uBAAsB;CACxB;AACA;EACE,qCAAoC;CACtC;AACA;EACE,YAAW;CACb;AACA;EACE,YAAW;EACX,aAAY;EACZ,kBAAiB;EACjB,YAAW;EACX,gDAAwD;EACxD,4BAA2B;EAC3B,6BAA4B;EAC5B,6BAA4B;EAC5B,uBAAsB;EACtB,iBAAgB;EAChB,mBAAkB;EAClB,kBAAiB;EACjB,YAAW;CACb;;AAEA;EACE,YAAW;EACX,aAAY;EACZ,aAAY;CACd;AACA;EACE,YAAW;EACX,aAAY;EACZ,aAAY;EACZ,mBAAkB;EAClB,iCAAgC;CAClC;AACA;EACE,YAAW;EACX,aAAY;EACZ,aAAY;EACZ,mBAAkB;CACpB;AACA;EACE,YAAW;EACX,aAAY;EACZ,aAAY;EACZ,mBAAkB;EAClB,iCAAgC;CAClC;AACA;GACG,YAAW;EACZ,aAAY;EACZ,aAAY;CACd;AACA;EACE,gBAAe;EACf,iBAAgB;EAChB,YAAW;EACX,0BAAyB;EACzB,YAAW;CACb;AACA;EACE,YAAW;EACX,aAAY;EACZ,aAAY;EACZ,iBAAgB;CAClB;AACA;EACE,YAAW;EACX,aAAY;EACZ,YAAW;CACb;AACA;EACE,YAAW;EACX,gBAAe;CACjB;AACA;EACE,WAAU;EACV,aAAY;EACZ,YAAW;EACX,kBAAiB;CACnB;AACA;EACE,gBAAe;EACf,iBAAgB;EAChB,YAAW;EACX,gBAAe;CACjB;AACA;EACE,gBAAe;EACf,iBAAgB;EAChB,YAAW;EACX,sBAAqB;;CAEvB;AACA;EACE,YAAW;CACb;AACA;GACG,YAAW;CACd;AACA;EACE,YAAW;CACb;AACA;EACE,YAAW;EACX,YAAW;EACX,aAAY;EACZ,iBAAgB;CAClB;AACA;EACE,WAAU;EACV,aAAY;CACd;AACA;EACE,sBAAqB;EACrB,mBAAkB;EAClB,iBAAgB;CAClB;AACA;EACE,gBAAe;EACf,YAAW;EACX,sBAAqB;GACpB,2BAA0B;CAC7B;AACA;EACE,YAAW;CACb;AACA;EACE,mBAAkB;CACpB;AACA;EACE,YAAW;EACX,aAAY;EACZ,aAAY;EACZ,iBAAgB;CAClB;AACA;GACG,YAAW;EACZ,aAAY;EACZ,aAAY;EACZ,iBAAgB;CAClB;AACA;EACE,YAAW;EACX,aAAY;EACZ,kBAAiB;EACjB,iBAAgB;EAChB,mBAAkB;EAClB,6CAA4C;EAC5C,uBAAsB;EACtB,gBAAe;EACf,iBAAgB;EAChB,kBAAiB;EACjB,YAAW;CACb;AACA;EACE,aAAY;EACZ,aAAY;EACZ,gBAAe;EACf,mBAAkB;EAClB,YAAW;EACX,0BAAyB;EACzB,iCAAgC;EAChC,YAAW;EACX,gBAAe;CACjB;AACA;EACE,iBAAgB;CAClB;AACA;EACE,YAAW;EACX,aAAY;EACZ,aAAY;EACZ,iBAAgB;EAChB,oBAAmB;CACrB;AACA;EACE,gBAAe;EACf,mBAAkB;EAClB,YAAW;CACb;AACA;EACE,mBAAkB;EAClB,0CAAmD;EACnD,WAAU;EACV,UAAS;EACT,YAAW;EACX,aAAY;CACd;AACA;EACE,gBAAe;EACf,mBAAkB;EAClB,0BAAyB;EACzB,kBAAiB;CACnB;AACA;EACE,YAAW;CACb;AACA,mBAAkB;AAClB;EACE;;IAEE,YAAW;IACX,aAAY;IACZ,kBAAiB;IACjB,YAAW;IACX,gDAAwD;IACxD,4BAA2B;IAC3B,6BAA4B;IAC5B,6BAA4B;IAC5B,uBAAsB;IACtB,iBAAgB;IAChB,mBAAkB;IAClB,kBAAiB;IACjB,YAAW;GACb;EACA;IACE,yBAAwB;IACxB,kBAAiB;IACjB,qBAAoB;GACtB;EACA;IACE,cAAa;GACf;;CAEF","file":"Footer.css","sourcesContent":["*{\r\n margin:0px;\r\n padding: 0px;\r\n box-sizing: border-box;\r\n}\r\nbody{\r\n font-family: 'Open Sans', sans-serif;\r\n}\r\n.clr{\r\n clear: both;\r\n}\r\n.footer-wrapper{\r\n width: 100%;\r\n height: auto;\r\n min-height: 250px;\r\n margin:auto;\r\n background-image: url(../../static/images/footer-bg.jpg);\r\n background-position: center;\r\n background-repeat: no-repeat;\r\n background-attachment: fixed;\r\n background-size: cover;\r\n overflow: hidden;\r\n position: absolute;\r\n padding-top: 75px;\r\n bottom: 0px;\r\n}\r\n\r\n.footer-mid-part{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n}\r\n.footer-section-one{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n padding: 20px 20px;\r\n background: rgba(255,255,255,.1);\r\n}\r\n.footer-section-two{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n padding: 20px 20px;\r\n}\r\n.footer-section-three{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n padding: 20px 20px;\r\n background: rgba(255,255,255,.1);\r\n}\r\n.footer-heading{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n}\r\n.footer-heading h2{\r\n font-size: 18px;\r\n text-align: left;\r\n color: #fff;\r\n text-transform: uppercase;\r\n margin: 0px;\r\n}\r\n.footer-contact-box{\r\n width: 100%;\r\n height: auto;;\r\n margin: auto;\r\n margin-top: 13px;\r\n}\r\n.footer-contact-icon{\r\n width: 25px;\r\n height: 25px;\r\n float: left;\r\n}\r\n.footer-contact-icon i{\r\n color: #fff;\r\n font-size: 20px;\r\n}\r\n.footer-contact-text{\r\n width: 85%;\r\n height: auto;\r\n float: left;\r\n margin-left: 10px;\r\n}\r\n.footer-contact-text p{\r\n font-size: 14px;\r\n text-align: left;\r\n color: #fff;\r\n cursor: pointer;\r\n}\r\n.footer-contact-text p a{\r\n font-size: 14px;\r\n text-align: left;\r\n color: #fff;\r\n text-decoration: none;\r\n\r\n}\r\n.footer-contact-text p:hover{\r\n color: #f00;\r\n}\r\n.footer-contact-box:hover .footer-contact-icon i{\r\n color: #f00;\r\n}\r\n.footer-contact-box:hover .footer-contact-text p a{\r\n color: #f00;\r\n}\r\n.footer-link{\r\n width: 100%;\r\n height:auto;\r\n margin: auto;\r\n margin-top: 20px;\r\n}\r\n.footer-link ul{\r\n margin:0px;\r\n padding: 0px;\r\n}\r\n.footer-link ul li{\r\n list-style-type: none;\r\n text-align: center;\r\n padding-top: 5px;\r\n}\r\n.footer-link ul li a{\r\n font-size: 14px;\r\n color: #fff;\r\n text-decoration: none;\r\n text-transform: capitalize;;\r\n}\r\n.footer-link ul li a:hover{\r\n color: #f00;\r\n}\r\n.footer-section-two .footer-heading h2{\r\n text-align: center;\r\n}\r\n.footer-form{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n margin-top: 20px;\r\n}\r\n.footer-form-box{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n margin-top: 20px;\r\n}\r\n.footer-form-style{\r\n width: 100%;\r\n height: 40px;\r\n border-left: none;\r\n border-top: none;\r\n border-right: none;\r\n border-bottom:1px solid rgba(255,255,255,.1);\r\n background:transparent;\r\n font-size: 14px;\r\n text-align: left;\r\n padding: 0px 10px;\r\n color: #fff;\r\n}\r\n.footer-form-submit-style{\r\n width: 129px;\r\n height: 35px;\r\n font-size: 16px;\r\n text-align: center;\r\n color: #fff;\r\n text-transform: uppercase;\r\n background: rgba(255,255,255,.5);\r\n border:none;\r\n margin-top: 1px;\r\n}\r\n.footer-form-submit-style:active{\r\n background: #f00;\r\n}\r\n.footer-bottom{\r\n width: 100%;\r\n height: auto;\r\n margin: auto;\r\n margin-top: 10px;\r\n margin-bottom: 10px;\r\n}\r\n.footer-bottom{\r\n font-size: 14px;\r\n text-align: center;\r\n color: #fff;\r\n}\r\n.top-img{\r\n position: absolute;\r\n background: url(../../static/images/top-divder.png);\r\n top: -20px;\r\n left: 0px;\r\n width: 100%;\r\n height: 55px;\r\n}\r\nh1{\r\n font-size: 60px;\r\n text-align: center;\r\n text-transform: uppercase;\r\n padding-top: 30px;\r\n}\r\nh1 span{\r\n color: #f00;\r\n}\r\n/*RESPONSIVE CODE*/\r\n@media only screen and (max-width: 1199px){\r\n .footer-wrapper{\r\n \r\n width: 100%;\r\n height: auto;\r\n min-height: 250px;\r\n margin:auto;\r\n background-image: url(../../static/images/footer-bg.jpg);\r\n background-position: center;\r\n background-repeat: no-repeat;\r\n background-attachment: fixed;\r\n background-size: cover;\r\n overflow: hidden;\r\n position: absolute;\r\n padding-top: 75px;\r\n bottom: 0px;\r\n }\r\n h1{\r\n font-size: 4vw!important;\r\n padding-top: 10px;\r\n padding-bottom: 10px;\r\n }\r\n .footer-section-one{\r\n padding: 12px;\r\n }\r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n"],"sourceRoot":""}]);
// exports
/***/ })
})
//# sourceMappingURL=cms.4810314b554e6d8bacba.hot-update.js.map |
const CustomError = require("../extensions/custom-error");
module.exports = function createDreamTeam(members) {
if(Array.isArray(members)) {
let dreamTeam = members.map(item => {
if (typeof item === "string") {
let charItem = item.trim();
return charItem[0].toUpperCase();
}
}).sort().join("");
return dreamTeam;
}
return false;
}; |
describe('c3 chart domain', function () {
'use strict';
var chart;
var args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
},
axis: {
y: {},
y2: {}
}
};
beforeEach(function (done) {
chart = window.initChart(chart, args, done);
});
describe('axis.y.min', function () {
it('should change axis.y.min to -100', function () {
args.axis.y.min = -100;
expect(true).toBeTruthy();
});
it('should be set properly when smaller than max of data', function () {
var domain = chart.internal.y.domain();
expect(domain[0]).toBe(-150);
expect(domain[1]).toBe(450);
});
it('should change axis.y.min to 500', function () {
args.axis.y.min = 500;
expect(true).toBeTruthy();
});
it('should be set properly when bigger than max of data', function () {
var domain = chart.internal.y.domain();
expect(domain[0]).toBe(499);
expect(domain[1]).toBe(511);
});
it('should change axis.y.min to undefined', function () {
args.axis.y.min = undefined;
expect(true).toBeTruthy();
});
});
describe('axis.y.max', function () {
it('should change axis.y.max to 1000', function () {
args.axis.y.max = 1000;
expect(true).toBeTruthy();
});
it('should be set properly when bigger than min of data', function () {
var domain = chart.internal.y.domain();
expect(domain[0]).toBe(-89);
expect(domain[1]).toBe(1099);
});
it('should change axis.y.max to 0', function () {
args.axis.y.max = 0;
expect(true).toBeTruthy();
});
it('should be set properly when smaller than min of data', function () {
var domain = chart.internal.y.domain();
expect(domain[0]).toBe(-11);
expect(domain[1]).toBe(1);
});
});
describe('axis.y.padding', function () {
it('should change axis.y.max to 1000', function () {
args = {
data: {
columns: [
['data1', 10, 20, 10, 40, 15, 25],
['data2', 50, 40, 30, 45, 25, 45]
]
},
axis: {
y: {
padding: 200,
}
}
};
expect(true).toBeTruthy();
});
it('should be set properly when bigger than min of data', function () {
var domain = chart.internal.y.domain();
expect(domain[0]).toBeCloseTo(-9, -1);
expect(domain[1]).toBeCloseTo(69, -1);
});
it('should change axis.y.max to 1000 with top/bottom padding', function () {
args = {
data: {
columns: [
['data1', 10, 20, 10, 40, 15, 25],
['data2', 50, 40, 30, 45, 25, 45]
]
},
axis: {
y: {
padding: {
top: 200,
bottom: 200
}
}
}
};
expect(true).toBeTruthy();
});
it('should be set properly when bigger than min of data', function () {
var domain = chart.internal.y.domain();
expect(domain[0]).toBeCloseTo(-9, -1);
expect(domain[1]).toBeCloseTo(69, -1);
});
});
});
|
/**
* Exposes REST methods of Elasticsearch
*
* @module services/elasticsearch
* @author Michał Borzęcki
* @copyright (C) 2019 ACK CYFRONET AGH
* @license This software is released under the MIT license cited in 'LICENSE.txt'.
*/
import Service, { inject as service } from '@ember/service';
export default Service.extend({
appProxy: service(),
/**
* Performs request to Elasticsearch.
* @param {string} method one of `get`, `post`, `put`, `delete`
* @param {string} indexName
* @param {string} path url (without host and index)
* @param {Object|undefined} body request body
* @returns {Promise<any>} request result
*/
request(method, indexName, path, body) {
const dataRequest = this.get('appProxy.dataRequest');
return dataRequest({
method,
indexName,
path,
body: JSON.stringify(body),
});
},
/**
* Makes a GET request
* @param {string} indexName
* @param {string} path
* @returns {Promise<any>}
*/
fetch(indexName, path) {
return this.request('get', indexName, path);
},
/**
* Makes a POST request
* @param {string} indexName
* @param {string} path
* @param {any} body
* @returns {Promise<any>}
*/
post(indexName, path, body) {
return this.request('post', indexName, path, body);
},
});
|
var inflect = require('i');
var _ = require('lodash');
/**
* Displays the singular or plural of a string based on a number
* or number of items in an array.
*
* If arity is 1, returns the plural form of the word.
*
* @param {String} count
* @param {String} singular string
* @param {String} plural string
* @return {String} singular or plural, * is replaced with count
* @api public
*/
exports.plural = function (count, sn, pl) {
if (arguments.length === 1) {
return inflect.pluralize(count);
}
if (typeof sn !== 'string') sn = '';
if (!pl) {
pl = inflect.pluralize(sn);
}
if (typeof count === 'string') {
count = Number(count);
} else if (typeof count !== 'number') {
count = _.size(count);
}
return (count === 1 ? sn : pl).replace('*', count);
};
/**
* Converts the first letter in a string to uppercase
*
* @param {String} str
* @return {String} Str
* @api public
*/
exports.upcase = function (str) {
if (str && str.toString) str = str.toString();
if (typeof str !== 'string' || !str.length) return '';
return (str.substr(0, 1).toUpperCase() + str.substr(1));
};
/**
* Converts the first letter in a string to lowercase
*
* @param {String} Str
* @return {String} str
* @api public
*/
exports.downcase = function (str) {
if (str && str.toString) str = str.toString();
if (typeof str !== 'string' || !str.length) return '';
return (str.substr(0, 1).toLowerCase() + str.substr(1));
};
/**
* Converts a string to title case
*
* @param {String} str
* @return {String} Title Case form of str
* @api public
*/
exports.titlecase = function (str) {
if (str && str.toString) str = str.toString();
if (typeof str !== 'string' || !str.length) return '';
str = str.replace(/([a-z])([A-Z])/g, '$1 $2');
var parts = str.split(/\s|_|\-/);
for (var i = 0; i < parts.length; i++) {
if (parts[i] && !/^[A-Z0-9]+$/.test(parts[i])) {
parts[i] = exports.upcase(parts[i]);
}
}
return _.compact(parts).join(' ');
};
/**
* Converts a string to camel case
*
* @param {String} str
* @param {Boolean} lowercaseFirstWord
* @return {String} camel-case form of str
* @api public
*/
exports.camelcase = function (str, lc) {
return inflect.camelize(str, !(lc));
};
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { resolve } from 'path';
import init from './init';
import './server/build_fix';
import { mappings } from './server/mappings';
import { CANVAS_APP } from './common/lib';
export function canvas(kibana) {
return new kibana.Plugin({
id: CANVAS_APP,
configPrefix: 'xpack.canvas',
require: ['kibana', 'elasticsearch', 'xpack_main', 'interpreter'],
publicDir: resolve(__dirname, 'public'),
uiExports: {
app: {
title: 'Canvas',
description: 'Data driven workpads',
icon: 'plugins/canvas/icon.svg',
euiIconType: 'canvasApp',
main: 'plugins/canvas/app',
},
styleSheetPaths: resolve(__dirname, 'public/style/index.scss'),
hacks: [
// window.onerror override
'plugins/canvas/lib/window_error_handler.js',
],
home: ['plugins/canvas/register_feature'],
mappings,
},
config: Joi => {
return Joi.object({
enabled: Joi.boolean().default(true),
indexPrefix: Joi.string().default('.canvas'),
}).default();
},
init,
});
}
|
import { viewCls } from '../../services/api/cls'
import { viewIxps } from '../../services/api/ixps'
import { viewCable } from '../../services/api/cables'
import { viewFacility } from '../../services/api/facs'
const state = {
bounds: [],
points: [],
focus: null,
filter: ['all'],
easePoint: null,
hasToEase: false,
currentSelection: null
}
const mutations = {
CURRENT_SELECTION(state, selection) {
state.currentSelection = selection
},
CURRENT_MAP_FILTER(state, filter) {
state.filter = filter
},
MAP_BOUNDS(state, bounds) {
state.bounds = bounds
},
MAP_FOCUS_ON(state, focus) {
state.focus = focus
},
MAP_POINTS(state, points) {
state.points = points
},
HAS_TO_EASE_TO(state, bool) {
state.hasToEase = bool
},
EASE_POINT(state, easePoint) {
state.easePoint = easePoint
if (easePoint && easePoint.hasToEase) {
state.hasToEase = easePoint.hasToEase
}
}
}
const actions = {
async getCableData({ commit }, data) {
const res = await viewCable(data)
if (res && res.data.r && res.data.r.length) {
commit('CURRENT_SELECTION', res.data.r[0])
} else {
commit('CURRENT_SELECTION', null)
}
},
async getFacilityData({ commit }, data) {
const res = await viewFacility(data)
if (res && res.data && res.data.r.length) {
commit('CURRENT_SELECTION', res.data.r[0])
} else {
commit('CURRENT_SELECTION', null)
}
return res
},
async getClsData({ commit }, data) {
const res = await viewCls(data)
if (res && res.data && res.data.r.length) {
commit('CURRENT_SELECTION', res.data.r[0])
} else {
commit('CURRENT_SELECTION', null)
}
return res
},
async getIxpsData({ commit }, data) {
const res = await viewIxps(data)
if (res && res.data && res.data.r.length) {
commit('CURRENT_SELECTION', res.data.r[0])
} else {
commit('CURRENT_SELECTION', null)
}
return res
}
}
export default {
namespaced: true,
state,
actions,
mutations
}
|
from datetime import datetime
from google.cloud import texttospeech
def generate_audio_file(article_item, local_path, audio_filename):
ttsc = texttospeech.TextToSpeechClient()
text2syn_dt = datetime.fromtimestamp(article_item['publication_datetime'] / 1000).strftime('%d-%m-%Y')
text2syn_pre = 'This audio reader article is provided to you by Dow Jones. \n\
Generated within the audio news reader demo application.'
text2syn_head = 'Published on <say-as interpret-as="date" format="dd-mm-yyyy \
detail="1">{}</say-as> by {}'.format(text2syn_dt, article_item['publisher_name'])
text2syn_title = article_item['title']
text2syn_body = article_item['body']
text2syn_post = 'End of the Audio Article.'
text2syn_full = '<speak>{} <break time="2s"/> {} <break time="2s"/> {} <break time="2s"/> {} <break time="3s"/>\
{}</speak>'.format(text2syn_pre, text2syn_head, text2syn_title, text2syn_body, text2syn_post)
synthesis_input = texttospeech.types.SynthesisInput(ssml=text2syn_full)
voice = texttospeech.types.VoiceSelectionParams(
language_code='en-US',
ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
response = ttsc.synthesize_speech(synthesis_input, voice, audio_config)
print("INFO Speech-to-Text API response received")
with open(local_path, 'wb') as out:
out.write(response.audio_content)
print("INFO Audio file {} was copied locally".format(audio_filename))
return audio_filename
|
/*
* ! UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.QuickViewPage
sap.ui.define([
'jquery.sap.global', './library', 'sap/ui/core/Control',
'sap/ui/core/IconPool', 'sap/ui/layout/form/SimpleForm',
'sap/ui/layout/VerticalLayout', 'sap/ui/layout/HorizontalLayout',
'./Page', './Button', './Bar',
'./Title', './Image', './Link', './Text',
'./Label', './HBox', 'sap/ui/core/Icon', 'sap/ui/core/Title',
'sap/ui/core/CustomData', 'sap/ui/core/library', 'sap/ui/layout/library'],
function(jQuery, library, Control,
IconPool, SimpleForm,
VerticalLayout, HorizontalLayout,
Page, Button, Bar,
Title, Image, Link, Text,
Label, HBox, Icon, CoreTitle,
CustomData, coreLibrary, layoutLibrary) {
"use strict";
// shortcut for sap.ui.layout.form.SimpleFormLayout
var SimpleFormLayout = layoutLibrary.form.SimpleFormLayout;
// shortcut for sap.ui.core.TitleLevel
var CoreTitleLevel = coreLibrary.TitleLevel;
// shortcut for sap.m.QuickViewGroupElementType
var QuickViewGroupElementType = library.QuickViewGroupElementType;
// shortcut for sap.m.ButtonType
var ButtonType = library.ButtonType;
/**
* Constructor for a new QuickViewPage.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class QuickViewPage consists of a page header, an object icon or image,
* an object name with short description, and an object information divided in groups.
* The control uses the sap.m.SimpleForm control to display information.
*
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.50.7
*
* @constructor
* @public
* @since 1.28.11
* @alias sap.m.QuickViewPage
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var QuickViewPage = Control.extend("sap.m.QuickViewPage", /** @lends sap.m.QuickViewPage.prototype */ {
metadata: {
library: "sap.m",
properties: {
/**
* Page id
*/
pageId: {
type: "string",
group: "Misc",
defaultValue: ""
},
/**
* Specifies the text displayed in the header of the control.
*/
header: {
type: "string",
group: "Misc",
defaultValue: ""
},
/**
* Specifies the text displayed in the header of the content section of the control.
*/
title: {
type: "string",
group: "Misc",
defaultValue: ""
},
/**
* Specifies the URL which opens when the title or the thumbnail is clicked.
*/
titleUrl: {
type: "string",
group: "Misc",
defaultValue: ""
},
/**
* Specifies the application which provides target and param configuration for cross-application navigation from the 'page header'.
*/
crossAppNavCallback : {
type: "object",
group: "Misc"
},
/**
* Specifies the text displayed under the header of the content section
*/
description: {
type: "string",
group: "Misc",
defaultValue: ""
},
/**
* Specifies the URL of the icon displayed under the header of the page
*/
icon: {
type: "string",
group: "Misc",
defaultValue: ""
}
},
defaultAggregation: "groups",
aggregations: {
/**
* QuickViewGroup consists of a title (optional) and an entity of group elements.
*/
groups: {
type: "sap.m.QuickViewGroup",
multiple: true,
singularName: "group",
bindable: "bindable"
}
}
}
});
QuickViewPage.prototype.init = function() {
this._oResourceBundle = sap.ui.getCore().getLibraryResourceBundle('sap.m');
//see API docu for sap.ushell.services.CrossApplicationNavigation
var fGetService = sap.ushell && sap.ushell.Container && sap.ushell.Container.getService;
if (fGetService) {
this.oCrossAppNavigator = fGetService("CrossApplicationNavigation");
}
};
/**
* Called before the control is rendered.
* @private
*/
QuickViewPage.prototype.onBeforeRendering = function() {
this._destroyPageContent();
this._createPageContent();
};
/**
* Returns page content containing the header and the form.
* @private
* @returns {Object} Object containing the header and the form
*/
QuickViewPage.prototype.getPageContent = function() {
return this._mPageContent;
};
/**
* Sets context containing navigation information.
* @param {Object} context Object containing specific navigation data.
* @private
*/
QuickViewPage.prototype.setNavContext = function (context) {
this._mNavContext = context;
};
/**
* Returns context containing navigation information.
* @private
* @returns {Object} Object containing specific navigation data
*/
QuickViewPage.prototype.getNavContext = function () {
return this._mNavContext;
};
/**
* Sets page title control.
* @param {sap.ui.core.Control} title The control that is displayed in the title of the page.
* @private
*/
QuickViewPage.prototype.setPageTitleControl = function (title) {
this._oPageTitle = title;
};
/**
* Returns page title control.
* @private
* @returns {sap.ui.core.Control} The control displayed in the title
*/
QuickViewPage.prototype.getPageTitleControl = function () {
return this._oPageTitle;
};
/**
* Helper function that creates a new {@link sap.m.Page} and adds content to it.
* @returns {sap.m.Page} The created page
* @private
*/
QuickViewPage.prototype._createPage = function () {
var mPageContent = this._createPageContent();
var mNavContext = this.getNavContext();
var oPage;
if (this._oPage) {
oPage = this._oPage;
oPage.destroyContent();
oPage.setCustomHeader(new Bar());
} else {
oPage = this._oPage = new Page(mNavContext.quickViewId + '-' + this.getPageId(), {
customHeader : new Bar()
});
oPage.addEventDelegate({
onAfterRendering: this.onAfterRenderingPage
}, this);
}
if (mPageContent.header) {
oPage.addContent(mPageContent.header);
}
oPage.addContent(mPageContent.form);
var oCustomHeader = oPage.getCustomHeader();
oCustomHeader.addContentMiddle(
new Title({
text : this.getHeader()
}).addStyleClass("sapMQuickViewTitle")
);
if (mNavContext.hasBackButton) {
oCustomHeader.addContentLeft(
new Button({
type : ButtonType.Back,
tooltip : this._oResourceBundle.getText("PAGE_NAVBUTTON_TEXT"),
press : function() {
if (mNavContext.navContainer) {
mNavContext.quickView._setNavOrigin(null);
mNavContext.navContainer.back();
}
}
})
);
}
if (mNavContext.popover && sap.ui.Device.system.phone) {
oCustomHeader.addContentRight(
new Button({
icon : IconPool.getIconURI("decline"),
press : function() {
mNavContext.popover.close();
}
})
);
}
oPage.addStyleClass('sapMQuickViewPage');
return oPage;
};
QuickViewPage.prototype.onAfterRenderingPage = function () {
if (this._bItemsChanged) {
var mNavContext = this.getNavContext();
if (mNavContext) {
mNavContext.quickView._restoreFocus();
}
this._bItemsChanged = false;
}
};
/**
* Helper function that creates the content of a QuickViewPage and returns it as an object
* with form and header properties.
* @returns {{form: sap.ui.layout.form.SimpleForm, header: sap.ui.layout.HorizontalLayout}}
* @private
*/
QuickViewPage.prototype._createPageContent = function () {
var oForm = this._createForm();
var oHeader = this._getPageHeaderContent();
// add ARIA title to the form
var oPageTitleControl = this.getPageTitleControl();
if (oHeader && oPageTitleControl) {
oForm.addAriaLabelledBy(oPageTitleControl);
}
this._mPageContent = {
form: oForm,
header: oHeader
};
return this._mPageContent;
};
/**
* Helper function that creates a form object based on the data in the groups of the QuickViewPage
* @returns {sap.ui.layout.form.SimpleForm} The form created based on the groups of the QuickViewPage
* @private
*/
QuickViewPage.prototype._createForm = function () {
var aGroups = this.getAggregation("groups"),
oForm = new SimpleForm({
maxContainerCols: 1,
editable: false,
layout: SimpleFormLayout.ResponsiveGridLayout
});
if (aGroups) {
for (var j = 0; j < aGroups.length; j++) {
if (aGroups[j].getVisible()) {
this._renderGroup(aGroups[j], oForm);
}
}
}
return oForm;
};
/**
* Helper function that creates the header of the QuickViewPage.
* @returns {sap.ui.layout.HorizontalLayout} The header of the QuickViewPage
* @private
*/
QuickViewPage.prototype._getPageHeaderContent = function() {
var oIcon,
oVLayout = new VerticalLayout(),
oHLayout = new HorizontalLayout(),
sIcon = this.getIcon(),
sTitle = this.getTitle(),
sDescription = this.getDescription(),
sTitleUrl = this.getTitleUrl();
if (!sIcon && !sTitle && !sDescription) {
return null;
}
if (sIcon) {
if (this.getIcon().indexOf("sap-icon") == 0) {
oIcon = new Icon({
src: sIcon,
decorative: !sTitleUrl,
useIconTooltip: false,
tooltip: sTitle
});
} else {
oIcon = new Image({
src: sIcon,
decorative: false,
tooltip: sTitle
}).addStyleClass("sapUiIcon");
}
oIcon.addStyleClass("sapMQuickViewThumbnail");
if (sTitleUrl) {
oIcon.attachPress(this._crossApplicationNavigation(this));
}
oHLayout.addContent(oIcon);
}
var oTitle;
if (sTitleUrl) {
oTitle = new Link({
text : sTitle,
href : sTitleUrl,
target : "_blank"
});
} else if (this.getCrossAppNavCallback()) {
oTitle = new Link({
text : sTitle
});
oTitle.attachPress(this._crossApplicationNavigation(this));
} else {
oTitle = new Title({
text : sTitle,
level : CoreTitleLevel.H1
});
}
this.setPageTitleControl(oTitle);
var oDescription = new Text({
text : sDescription
});
oVLayout.addContent(oTitle);
oVLayout.addContent(oDescription);
oHLayout.addContent(oVLayout);
return oHLayout;
};
/**
* Helper function that renders a QuickViewGroup in the QuickViewPage.
* @param {sap.m.QuickViewGroup} oGroup The group to be rendered.
* @param {sap.ui.layout.form.SimpleForm} oForm The form in which the group is rendered
* @private
*/
QuickViewPage.prototype._renderGroup = function(oGroup, oForm) {
var aElements = oGroup.getAggregation("elements");
var oCurrentGroupElement,
oCurrentGroupElementValue,
oLabel;
if (oGroup.getHeading()) {
oForm.addContent(new CoreTitle({
text : oGroup.getHeading(),
level : CoreTitleLevel.H2
}));
}
if (!aElements) {
return;
}
var mNavContext = this.getNavContext();
for (var k = 0; k < aElements.length; k++) {
oCurrentGroupElement = aElements[k];
if (!oCurrentGroupElement.getVisible()) {
continue;
}
oLabel = new Label({
text: oCurrentGroupElement.getLabel()
});
var sQuickViewId;
if (mNavContext) {
sQuickViewId = mNavContext.quickViewId;
}
oCurrentGroupElementValue = oCurrentGroupElement._getGroupElementValue(sQuickViewId);
oForm.addContent(oLabel);
if (!oCurrentGroupElementValue) {
// Add dummy text element so that the form renders the oLabel
oForm.addContent(new sap.m.Text({text : ""}));
continue;
}
oLabel.setLabelFor(oCurrentGroupElementValue.getId());
if (oCurrentGroupElement.getType() == QuickViewGroupElementType.pageLink) {
oCurrentGroupElementValue.attachPress(this._attachPressLink(this));
}
if (oCurrentGroupElement.getType() == QuickViewGroupElementType.mobile &&
!sap.ui.Device.system.desktop) {
var oSmsLink = new Icon({
src: IconPool.getIconURI("post"),
tooltip : this._oResourceBundle.getText("QUICKVIEW_SEND_SMS"),
decorative : false,
customData: [new CustomData({
key: "phoneNumber",
value: oCurrentGroupElement.getValue()
})],
press: this._mobilePress
});
var oBox = new HBox({
items: [oCurrentGroupElementValue, oSmsLink]
});
oForm.addContent(oBox);
} else {
oForm.addContent(oCurrentGroupElementValue);
}
}
};
/**
* Helper function used to navigate to another Fiori application (intent based navigation) or
* to an external link.
* This will be applicable only for the header link.
* @param {sap.m.QuickViewPage} that - The page from which the navigation starts
* @returns {Function} A function that executes the navigation
* @private
*/
QuickViewPage.prototype._crossApplicationNavigation = function (that) {
return function () {
if (that.getCrossAppNavCallback() && that.oCrossAppNavigator) {
var targetConfigCallback = that.getCrossAppNavCallback();
if (typeof targetConfigCallback == "function") {
var targetConfig = targetConfigCallback();
var href = that.oCrossAppNavigator.hrefForExternal(
{
target : {
semanticObject : targetConfig.target.semanticObject,
action : targetConfig.target.action
},
params : targetConfig.params
}
);
sap.m.URLHelper.redirect(href);
}
} else if (that.getTitleUrl()) {
window.open(that.getTitleUrl(), "_blank");
}
};
};
QuickViewPage.prototype._destroyPageContent = function() {
if (!this._mPageContent) {
return;
}
if (this._mPageContent.form) {
this._mPageContent.form.destroy();
}
if (this._mPageContent.header) {
this._mPageContent.header.destroy();
}
this._mPageContent = null;
};
QuickViewPage.prototype.exit = function() {
this._oResourceBundle = null;
if (this._oPage) {
this._oPage.destroy();
this._oPage = null;
} else {
this._destroyPageContent();
}
this._mNavContext = null;
};
/**
* Helper function used to attach click handler to links in the QuickViewPage
* that should lead to another QuickViewPage.
* @param {sap.m.QuickViewPage} that The page from which the navigation occurs.
* @returns {Function} A function executed when the link is clicked
* @private
*/
QuickViewPage.prototype._attachPressLink = function (that) {
var mNavContext = that.getNavContext();
return function (e) {
e.preventDefault();
var sPageId = this.getCustomData()[0].getValue();
if (mNavContext.navContainer && sPageId) {
mNavContext.quickView._setNavOrigin(this);
mNavContext.navContainer.to(sPageId);
}
};
};
/**
* Function executed when the sms icon in the QuickViewPage is clicked.
* @private
*/
QuickViewPage.prototype._mobilePress = function () {
var sms = "sms://" + jQuery.sap.encodeURL(this.getCustomData()[0].getValue());
window.location.replace(sms);
};
/**
* Updates the contents of the page and sets the focus on the last focused element or
* on the first focusable element.
* @private
*/
QuickViewPage.prototype._updatePage = function () {
var mNavContext = this.getNavContext();
if (mNavContext && mNavContext.quickView._bRendered) {
this._bItemsChanged = true;
mNavContext.popover.focus();
if (mNavContext.quickView.indexOfPage(this) == 0) {
mNavContext.quickView._clearContainerHeight();
}
this._createPage();
// in some cases the popover has display:none style here,
// which delays the simple form re-arranging and an unwanted scrollbar might appear.
mNavContext.popover.$().css('display', 'block');
mNavContext.quickView._restoreFocus();
}
};
["setModel", "bindAggregation", "setAggregation", "insertAggregation", "addAggregation",
"removeAggregation", "removeAllAggregation", "destroyAggregation"].forEach(function (sFuncName) {
QuickViewPage.prototype["_" + sFuncName + "Old"] = QuickViewPage.prototype[sFuncName];
QuickViewPage.prototype[sFuncName] = function () {
var result = QuickViewPage.prototype["_" + sFuncName + "Old"].apply(this, arguments);
this._updatePage();
if (["removeAggregation", "removeAllAggregation"].indexOf(sFuncName) !== -1) {
return result;
}
return this;
};
});
QuickViewPage.prototype.setProperty = function () {
Control.prototype.setProperty.apply(this, arguments);
this._updatePage();
};
return QuickViewPage;
}, /* bExport= */true);
|
(function() {
'use strict';
/** @ngInject */
function ProfileModalController($uibModalInstance, profileService, libraryService, apiService) {
var vm = this;
vm.profile = profileService.getProfile();
vm.processing = false;
vm.updateProfile = function() {
vm.processing = true;
return apiService.updateProfile(vm.profile).then(function(result) {
vm.profile = result.data;
profileService.setProfile(result.data);
vm.dismiss();
}).catch(function(error) {
vm.profileError = error.message;
});
};
vm.dismiss = function() {
$uibModalInstance.dismiss();
};
}
angular.module('ndApp')
.controller('ProfileModalController', ProfileModalController);
})();
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
gulp.task('markups', function() {
function renameToHtml(path) {
path.extname = '.html';
}
return gulp.src(path.join(conf.paths.src, '/app/**/*.<%- props.htmlPreprocessor.extension %>'))
<% if (props.htmlPreprocessor.key === 'jade') { -%>
.pipe($.consolidate('jade', { basedir: conf.paths.src, doctype: 'html', pretty: ' ' })).on('error', conf.errorHandler('Jade'))
<% } else if (props.htmlPreprocessor.key === 'haml') { -%>
.pipe($.consolidate('haml')).on('error', conf.errorHandler('Haml'))
<% } else if (props.htmlPreprocessor.key === 'handlebars') { -%>
.pipe($.consolidate('handlebars')).on('error', conf.errorHandler('Handlebars'))
<% } -%>
.pipe($.rename(renameToHtml))
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve/app/')))
.pipe(browserSync.stream());
});
|
import numpy as np
import scipy.signal as signal
import scipy.interpolate as ip
from typing import List, Tuple
def firls(n : int, f, a, w=None) -> Tuple:
"""
FIR filter design using least-squares error minimization.
Calculate the filter coefficients for the linear-phase finite
impulse response (FIR) filter which has the best approximation
to the desired frequency response described by `f` and
`a` in the least squares sense (i.e., the integral of the
weighted mean-squared error within the specified bands is
minimized).
Parameters
----------
n : int
Filter order, specified as a real positive scalar. `n` must be even.
f : array_like
A monotonic nondecreasing sequence containing the band edges in
Hz. All elements must be non-negative and less than or equal to
1.
a : array_like
A sequence the same size as `f` containing the desired gain
at the start and end point of each band.
w : array_like, optional
A relative weighting to give to each band region when solving
the least squares problem. `w` has to be half the size of
`f`.
Returns
-------
system :a tuple of array_like describing the system.
The following gives the number of elements in the tuple and
the interpretation:
* (num, den)
"""
if n%2 == 1:
n += 1
#print('Warning: The filter order you inserted is even.')
#print(' The filter order changed to {}.'.format(n))
n += 1
num = signal.firls(n, f, a, weight=w)
den = 1
return num, den |
import warnings
import math
import numpy as np
from PIL import Image
class LBP:
"""
Class used to compute the Local Binary Patterns of an image and the resulting histograms.
It computes the matrix holding the local representation of the texture for each pixel, i.e. the comparison of each
pixel with its surrounding neighbours. Then from this matrix it can compute the normalized histogram of each cell
and the resulting feature vector obtained concatenating each cell's histogram
An instance of the LBP class holds the LBP matrix of the image used as constructor's parameter, computed during the
instantiation. The image is padded with zeros, for computing values on image edges.
The number of neighbours and their distance from the considered pixel can be specified as parameters, the offset
values are computed as equidistant points on a circumference, in clockwise direction starting from the middle-up
position, and approximated to the nearest integers in order to obtain the coordinates on the pixels matrix.
The number of neighbors influence the size of words (neighbors-bit words) and the size of the histogram, which range
is [0, 2^neighbor - 1].
For the histogram computation, the image is divided in the certain number of cells which shape is specified as
parameter. If the cells don't perfectly tile the matrix, the ones on the right and bottom border will be shrunken
and a warning will be displayed. The histogram of each cell is computed and normalized. A matrix of all histograms
organized as the cell's placement is saved as an attribute, together with a feature vector representing a view on
the flattened concatenation of all histograms.
Args:
image (PIL.Image): The image that has to be analyzed, it is internally converted in B/W with Image.convert('L')
cell_shape (int, int): The dimension of each cell in the LBP matrix on which the histograms are computed.
Default: (16, 16)
neighbors (int): The number of neighbors considered for each pixel. Default: 8
distance (int): The distance of the considered neighbors. Default: 1
fast (bool): If true, uses a numpy-efficient algorithm instead of the definition-like one. Default: True
Attributes:
matrix (numpy.ndarray): The Local Binary Patterns matrix computed during the LBP class instantiation
upon a specified image
histograms (numpy.ndarray): A matrix containing the cells' histograms, organized as the cells are arranged in
the Local Binary Patterns matrix
feature_vtr (numpy.ndarray): A view of the histograms matrix that concatenates all histograms in a single
vector. The histograms are ordered row by row, from left to right.
Equivalent to LBP(...).histograms.reshape(-1).
hist_bins (int): Number of bins, or buckets, used for each histogram. It is the maximum value that a
pixel's word can represent for the given number of neighbors specified
neighbors_offsets (numpy.ndarray): A matrix holding in the i-th row the row and column offsets needed to reach
the i-th neighbor of a pixel
"""
def __init__(self, image: Image, cell_shape=(16, 16), neighbors=8, distance=1, fast=True):
pixels = np.array(image.convert('L')) # pixels.dtype == np.uint8
# ===Histogram bins===
self.hist_bins = 2 ** neighbors
# ===Neighbor offsets===
self.neighbors_offsets = self._neighbors_offsets(neighbors, distance)
# ===LBP Matrix===
if fast:
self.matrix = self._local_binary_patterns(pixels, distance)
else:
self.matrix = self._naive_local_binary_patterns(pixels, distance)
# ===Histograms===
self.histograms = self._histograms(cell_shape)
self.feature_vtr = self.histograms.reshape(-1)
def _local_binary_patterns(self, pixels: np.ndarray, distance: int) -> np.ndarray:
"""Returns the Local Binary Patters matrix of the given pixels"""
# # The dtype of the lbp_matrix follows the maximum size of the integers it can contain. Defaults to uint8
# The pixel matrix is padded with with zeros so neighbors of pixels placed in the borders can be referenced
padded_pixels = np.pad(pixels, distance, constant_values=0)
# Compute the 3D matrix holding all neighbors for each position
neighbors = np.stack([self._shift(padded_pixels, offset, distance) for offset in self.neighbors_offsets])
neighbors = np.moveaxis(neighbors, 0, -1) # Rearrange the shape to be (m x n x neighbors)
# If the neighbor is greater or equal -> 1 (True); if the the center is greater -> 0 (False)
words = neighbors >= pixels[..., np.newaxis]
# Transform the binary arrays to a decimal value
lbp_matrix = self._words_to_decimals(words)
# The dtype follows the maximum size of the integers it can contain. With the default 8 neighbors, it is uint8
return lbp_matrix.astype(self._best_dtype(self.hist_bins))
def _histograms(self, cell_shape: (int, int)) -> np.ndarray:
"""Returns the histograms matrix on the LBP matrix attribute divided in cells of shape specified as parameter"""
# Raise a warning if the image can't be evenly divided and some cells have to be smaller
celled_shape = self.matrix.shape[0] / cell_shape[0], self.matrix.shape[1] / cell_shape[1]
if not celled_shape[0].is_integer() or not celled_shape[0].is_integer():
warnings.warn(f"The cell's shape {cell_shape} cannot perfectly tile the image's shape {self.matrix.shape}",
stacklevel=3)
celled_shape = tuple(int(math.ceil(dim)) for dim in celled_shape)
# List that every (n, n+1) couple represents the indices range of a cell
rows = [None, *range(cell_shape[0], self.matrix.shape[0], cell_shape[0]), None] # [None 16 32 ... 496 None]
cols = [None, *range(cell_shape[1], self.matrix.shape[1], cell_shape[1]), None]
histograms = np.array([[
np.histogram(self.matrix[rows[i]:rows[i + 1], cols[j]:cols[j + 1]],
bins=self.hist_bins, range=(0, self.hist_bins), density=True)[0]
for j in range(0, celled_shape[1])]
for i in range(0, celled_shape[0])])
return histograms
@staticmethod
def _neighbors_offsets(neighbors: int, distance: int) -> np.ndarray:
"""
Function to compute the offsets of a certain number of neighbors, at a given distance. The method finds the
desired number of equidistant neighbors on a circumference, starting from -π/2 in a counterclockwise direction
because in the matrix indexing going upwards means to decrease the index. The resulting offsets give the
neighbors in a clockwise direction starting from exactly above the center pixel.
Args:
neighbors (int): The number of neighbors considered
distance (int): The distance from the center pixel to the neighbors
Returns:
A matrix holding in the i-th row the row and column offsets needed to reach the i-th neighbor
"""
angles = - np.pi / 2 + np.arange(0, neighbors) * 2 * np.pi / neighbors
offsets = np.stack([np.sin(angles), np.cos(angles)], axis=1) * distance
# Rounding coordinates
return np.rint(offsets).astype(int)
@staticmethod
def _shift(padded_pixels: np.ndarray, offset: np.ndarray, padding: int) -> np.ndarray:
"""Takes the padded matrix and returns the view on the original matrix's position and shifted of the offset"""
coord = np.array([[padding, padding], np.array(padded_pixels.shape) - padding]) + offset
return padded_pixels[coord[0, 0]:coord[1, 0], coord[0, 1]:coord[1, 1]]
@staticmethod
def _words_to_decimals(words: np.ndarray) -> np.ndarray:
"""Function to compute the decimal value of an array of bits ordered from the most to the least significant"""
coefficients = (1 << np.arange(words.shape[-1])[::-1]) # [..., 128, 64, 32, 16, 8, 4, 2, 1]
return np.tensordot(words, coefficients, axes=([2], [0]))
@staticmethod
def _best_dtype(max_value: int) -> np.dtype:
"""Returns the best dtype for the LBP matrix, to save memory space """
neighbors = np.log2(max_value)
if neighbors <= 8:
bits = np.uint8
elif neighbors <= 16:
bits = np.uint16
elif neighbors <= 32:
bits = np.uint32
else:
bits = np.uint64
return np.dtype(bits)
def _naive_local_binary_patterns(self, pixels: np.ndarray, distance: int) -> np.ndarray:
# Slow implementation: ~6.2s on a 512x512 matrix
lbp_matrix = np.empty(pixels.shape)
# the pixel matrix is padded with with zeros so neighbors of pixels placed in the borders can be referenced
padded_pixels = np.pad(pixels, distance, constant_values=0)
for i in range(0, lbp_matrix.shape[0]):
for j in range(0, lbp_matrix.shape[1]):
neighbors_coord = (self.neighbors_offsets + [i, j] + distance).T
# Passing the rows and then the columns of the coordinates
neighbors = padded_pixels[neighbors_coord[0], neighbors_coord[1]]
# If the neighbor is greater or equal -> 1 (True); if the the center is greater -> 0 (False)
word = np.greater_equal(neighbors, pixels[i, j])
lbp_matrix[i, j] = word.dot(1 << np.arange(word.size)[::-1])
return lbp_matrix
|
(function ($) {
$.fn.touchwipe = function (settings) {
var config = {
min_move_x: 20,
min_move_y: 20,
wipeLeft: function () {},
wipeRight: function () {},
wipeUp: function () {},
wipeDown: function () {},
preventDefaultEvents: true,
};
if (settings) $.extend(config, settings);
this.each(function () {
var startX;
var startY;
var isMoving = false;
function cancelTouch() {
this.removeEventListener("touchmove", onTouchMove);
startX = null;
isMoving = false;
}
function onTouchMove(e) {
if (config.preventDefaultEvents) {
e.preventDefault();
}
if (isMoving) {
var x = e.touches[0].pageX;
var y = e.touches[0].pageY;
var dx = startX - x;
var dy = startY - y;
if (Math.abs(dx) >= config.min_move_x) {
cancelTouch();
if (dx > 0) {
config.wipeLeft();
} else {
config.wipeRight();
}
} else if (Math.abs(dy) >= config.min_move_y) {
cancelTouch();
if (dy > 0) {
config.wipeDown();
} else {
config.wipeUp();
}
}
}
}
function onTouchStart(e) {
if (e.touches.length == 1) {
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
isMoving = true;
this.addEventListener("touchmove", onTouchMove, false);
}
}
if ("ontouchstart" in document.documentElement) {
this.addEventListener("touchstart", onTouchStart, false);
}
});
return this;
};
})(jQuery);
(function ($) {
var liveUpdatingTargetSelectors = {};
var liveUpdaterIntervalId;
var liveUpdaterRunning = false;
var defaultSettings = { ellipsis: "...", setTitle: "never", live: false };
$.fn.ellipsis = function (selector, options) {
var subjectElements, settings;
subjectElements = $(this);
if (typeof selector !== "string") {
options = selector;
selector = undefined;
}
settings = $.extend({}, defaultSettings, options);
settings.selector = selector;
subjectElements.each(function () {
var elem = $(this);
ellipsisOnElement(elem, settings);
});
if (settings.live) {
addToLiveUpdater(subjectElements.selector, settings);
} else {
removeFromLiveUpdater(subjectElements.selector);
}
return this;
};
function ellipsisOnElement(containerElement, settings) {
var containerData = containerElement.data("jqae");
if (!containerData) containerData = {};
var wrapperElement = containerData.wrapperElement;
if (!wrapperElement) {
wrapperElement = containerElement.wrapInner("<div/>").find(">div");
wrapperElement.css({ margin: 0, padding: 0, border: 0 });
}
var wrapperElementData = wrapperElement.data("jqae");
if (!wrapperElementData) wrapperElementData = {};
var wrapperOriginalContent = wrapperElementData.originalContent;
if (wrapperOriginalContent) {
wrapperElement = wrapperElementData.originalContent
.clone(true)
.data("jqae", { originalContent: wrapperOriginalContent })
.replaceAll(wrapperElement);
} else {
wrapperElement.data("jqae", {
originalContent: wrapperElement.clone(true),
});
}
containerElement.data("jqae", {
wrapperElement: wrapperElement,
containerWidth: containerElement.width(),
containerHeight: containerElement.height(),
});
var containerElementHeight = containerElement.height();
var wrapperOffset =
(parseInt(containerElement.css("padding-top"), 10) || 0) +
(parseInt(containerElement.css("border-top-width"), 10) || 0) -
(wrapperElement.offset().top - containerElement.offset().top);
var deferAppendEllipsis = false;
var selectedElements = wrapperElement;
if (settings.selector)
selectedElements = $(
wrapperElement.find(settings.selector).get().reverse()
);
selectedElements.each(function () {
var selectedElement = $(this),
originalText = selectedElement.text(),
ellipsisApplied = false;
if (
wrapperElement.innerHeight() - selectedElement.innerHeight() >
containerElementHeight + wrapperOffset
) {
selectedElement.remove();
} else {
removeLastEmptyElements(selectedElement);
if (selectedElement.contents().length) {
if (deferAppendEllipsis) {
getLastTextNode(selectedElement).get(0).nodeValue +=
settings.ellipsis;
deferAppendEllipsis = false;
}
while (
wrapperElement.innerHeight() >
containerElementHeight + wrapperOffset
) {
ellipsisApplied = ellipsisOnLastTextNode(
selectedElement
);
if (ellipsisApplied) {
removeLastEmptyElements(selectedElement);
if (selectedElement.contents().length) {
getLastTextNode(selectedElement).get(
0
).nodeValue += settings.ellipsis;
} else {
deferAppendEllipsis = true;
selectedElement.remove();
break;
}
} else {
deferAppendEllipsis = true;
selectedElement.remove();
break;
}
}
if (
(settings.setTitle == "onEllipsis" &&
ellipsisApplied) ||
settings.setTitle == "always"
) {
selectedElement.attr("title", originalText);
} else if (settings.setTitle != "never") {
selectedElement.removeAttr("title");
}
}
}
});
}
function ellipsisOnLastTextNode(element) {
var lastTextNode = getLastTextNode(element);
if (lastTextNode.length) {
var text = lastTextNode.get(0).nodeValue;
var pos = text.lastIndexOf(" ");
if (pos > -1) {
text = $.trim(text.substring(0, pos));
lastTextNode.get(0).nodeValue = text;
} else {
lastTextNode.get(0).nodeValue = "";
}
return true;
}
return false;
}
function getLastTextNode(element) {
if (element.contents().length) {
var contents = element.contents();
var lastNode = contents.eq(contents.length - 1);
if (lastNode.filter(textNodeFilter).length) {
return lastNode;
} else {
return getLastTextNode(lastNode);
}
} else {
element.append("");
var contents = element.contents();
return contents.eq(contents.length - 1);
}
}
function removeLastEmptyElements(element) {
if (element.contents().length) {
var contents = element.contents();
var lastNode = contents.eq(contents.length - 1);
if (lastNode.filter(textNodeFilter).length) {
var text = lastNode.get(0).nodeValue;
text = $.trim(text);
if (text == "") {
lastNode.remove();
return true;
} else {
return false;
}
} else {
while (removeLastEmptyElements(lastNode)) {}
if (lastNode.contents().length) {
return false;
} else {
lastNode.remove();
return true;
}
}
}
return false;
}
function textNodeFilter() {
return this.nodeType === 3;
}
function addToLiveUpdater(targetSelector, settings) {
liveUpdatingTargetSelectors[targetSelector] = settings;
if (!liveUpdaterIntervalId) {
liveUpdaterIntervalId = window.setInterval(function () {
doLiveUpdater();
}, 200);
}
}
function removeFromLiveUpdater(targetSelector) {
if (liveUpdatingTargetSelectors[targetSelector]) {
delete liveUpdatingTargetSelectors[targetSelector];
if (!liveUpdatingTargetSelectors.length) {
if (liveUpdaterIntervalId) {
window.clearInterval(liveUpdaterIntervalId);
liveUpdaterIntervalId = undefined;
}
}
}
}
function doLiveUpdater() {
if (!liveUpdaterRunning) {
liveUpdaterRunning = true;
for (var targetSelector in liveUpdatingTargetSelectors) {
$(targetSelector).each(function () {
var containerElement, containerData;
containerElement = $(this);
containerData = containerElement.data("jqae");
if (
containerData.containerWidth !=
containerElement.width() ||
containerData.containerHeight !=
containerElement.height()
) {
ellipsisOnElement(
containerElement,
liveUpdatingTargetSelectors[targetSelector]
);
}
});
}
liveUpdaterRunning = false;
}
}
})(jQuery);
(function ($) {
$.waterfall = function () {
var steps = [],
dfrd = $.Deferred(),
pointer = 0;
$.each(arguments, function (i, a) {
steps.push(function () {
var args = [].slice.apply(arguments),
d;
if (typeof a == "function") {
if (!((d = a.apply(null, args)) && d.promise)) {
d = $.Deferred()[d === false ? "reject" : "resolve"](d);
}
} else if (a && a.promise) {
d = a;
} else {
d = $.Deferred()[a === false ? "reject" : "resolve"](a);
}
d.fail(function () {
dfrd.reject.apply(dfrd, [].slice.apply(arguments));
}).done(function (data) {
pointer++;
args.push(data);
pointer == steps.length
? dfrd.resolve.apply(dfrd, args)
: steps[pointer].apply(null, args);
});
});
});
steps.length ? steps[0]() : dfrd.resolve();
return dfrd;
};
})(jQuery);
(function (factory) {
if (typeof define === "function" && define.amd) {
define(["jquery"], factory);
} else if (typeof exports === "object") {
factory(require("jquery"));
} else {
factory(jQuery);
}
})(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\");
}
try {
s = decodeURIComponent(s.replace(pluses, " "));
return config.json ? JSON.parse(s) : s;
} catch (e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = ($.cookie = function (key, value, options) {
if (arguments.length > 1 && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === "number") {
var days = options.expires,
t = (options.expires = new Date());
t.setTime(+t + days * 864e5);
}
return (document.cookie = [
encode(key),
"=",
stringifyCookieValue(value),
options.expires
? "; expires=" + options.expires.toUTCString()
: "",
options.path ? "; path=" + options.path : "",
options.domain ? "; domain=" + options.domain : "",
options.secure ? "; secure" : "",
].join(""));
}
var result = key ? undefined : {};
var cookies = document.cookie ? document.cookie.split("; ") : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split("=");
var name = decode(parts.shift());
var cookie = parts.join("=");
if (key && key === name) {
result = read(cookie, value);
break;
}
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
});
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) {
return false;
}
$.cookie(key, "", $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
});
("use strict");
var _createClass = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return call && (typeof call === "object" || typeof call === "function")
? call
: self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError(
"Super expression must either be null or a function, not " +
typeof superClass
);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true,
},
});
if (superClass)
Object.setPrototypeOf
? Object.setPrototypeOf(subClass, superClass)
: (subClass.__proto__ = superClass);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Emitter = (function () {
function Emitter() {
_classCallCheck(this, Emitter);
}
_createClass(Emitter, [
{
key: "on",
value: function on(event, fn) {
this._callbacks = this._callbacks || {};
if (!this._callbacks[event]) {
this._callbacks[event] = [];
}
this._callbacks[event].push(fn);
return this;
},
},
{
key: "emit",
value: function emit(event) {
this._callbacks = this._callbacks || {};
var callbacks = this._callbacks[event];
if (callbacks) {
for (
var _len = arguments.length,
args = Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
for (
var _iterator = callbacks,
_isArray = true,
_i = 0,
_iterator = _isArray
? _iterator
: _iterator[Symbol.iterator]();
;
) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var callback = _ref;
callback.apply(this, args);
}
}
return this;
},
},
{
key: "off",
value: function off(event, fn) {
if (!this._callbacks || arguments.length === 0) {
this._callbacks = {};
return this;
}
var callbacks = this._callbacks[event];
if (!callbacks) {
return this;
}
if (arguments.length === 1) {
delete this._callbacks[event];
return this;
}
for (var i = 0; i < callbacks.length; i++) {
var callback = callbacks[i];
if (callback === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
},
},
]);
return Emitter;
})();
var Dropzone = (function (_Emitter) {
_inherits(Dropzone, _Emitter);
_createClass(Dropzone, null, [
{
key: "initClass",
value: function initClass() {
this.prototype.Emitter = Emitter;
this.prototype.events = [
"drop",
"dragstart",
"dragend",
"dragenter",
"dragover",
"dragleave",
"addedfile",
"addedfiles",
"removedfile",
"thumbnail",
"error",
"errormultiple",
"processing",
"processingmultiple",
"uploadprogress",
"totaluploadprogress",
"sending",
"sendingmultiple",
"success",
"successmultiple",
"canceled",
"canceledmultiple",
"complete",
"completemultiple",
"reset",
"maxfilesexceeded",
"maxfilesreached",
"queuecomplete",
];
this.prototype.defaultOptions = {
url: null,
method: "post",
withCredentials: false,
timeout: 30000,
parallelUploads: 2,
uploadMultiple: false,
chunking: false,
forceChunking: false,
chunkSize: 2000000,
parallelChunkUploads: false,
retryChunks: false,
retryChunksLimit: 3,
maxFilesize: 256,
paramName: "file",
createImageThumbnails: true,
maxThumbnailFilesize: 10,
thumbnailWidth: 120,
thumbnailHeight: 120,
thumbnailMethod: "crop",
resizeWidth: null,
resizeHeight: null,
resizeMimeType: null,
resizeQuality: 0.8,
resizeMethod: "contain",
filesizeBase: 1000,
maxFiles: null,
headers: null,
clickable: true,
ignoreHiddenFiles: true,
acceptedFiles: null,
acceptedMimeTypes: null,
autoProcessQueue: true,
autoQueue: true,
addRemoveLinks: false,
previewsContainer: null,
hiddenInputContainer: "body",
capture: null,
renameFilename: null,
renameFile: null,
forceFallback: false,
dictDefaultMessage: "Drop files here to upload",
dictFallbackMessage:
"Your browser does not support drag'n'drop file uploads.",
dictFallbackText:
"Please use the fallback form below to upload your files like in the olden days.",
dictFileTooBig:
"File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",
dictInvalidFileType: "You can't upload files of this type.",
dictResponseError:
"Server responded with {{statusCode}} code.",
dictCancelUpload: "Cancel upload",
dictUploadCanceled: "Upload canceled.",
dictCancelUploadConfirmation:
"Are you sure you want to cancel this upload?",
dictRemoveFile: "Remove file",
dictRemoveFileConfirmation: null,
dictMaxFilesExceeded: "You can not upload any more files.",
dictFileSizeUnits: {
tb: "TB",
gb: "GB",
mb: "MB",
kb: "KB",
b: "b",
},
init: function init() {},
params: function params(files, xhr, chunk) {
if (chunk) {
return {
dzuuid: chunk.file.upload.uuid,
dzchunkindex: chunk.index,
dztotalfilesize: chunk.file.size,
dzchunksize: this.options.chunkSize,
dztotalchunkcount:
chunk.file.upload.totalChunkCount,
dzchunkbyteoffset:
chunk.index * this.options.chunkSize,
};
}
},
accept: function accept(file, done) {
return done();
},
chunksUploaded: function chunksUploaded(file, done) {
done();
},
fallback: function fallback() {
var messageElement = void 0;
this.element.className =
this.element.className +
" dz-browser-not-supported";
for (
var _iterator2 = this.element.getElementsByTagName(
"div"
),
_isArray2 = true,
_i2 = 0,
_iterator2 = _isArray2
? _iterator2
: _iterator2[Symbol.iterator]();
;
) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var child = _ref2;
if (/(^| )dz-message($| )/.test(child.className)) {
messageElement = child;
child.className = "dz-message";
break;
}
}
if (!messageElement) {
messageElement = Dropzone.createElement(
'<div class="dz-message"><span></span></div>'
);
this.element.appendChild(messageElement);
}
var span = messageElement.getElementsByTagName(
"span"
)[0];
if (span) {
if (span.textContent != null) {
span.textContent = this.options.dictFallbackMessage;
} else if (span.innerText != null) {
span.innerText = this.options.dictFallbackMessage;
}
}
return this.element.appendChild(this.getFallbackForm());
},
resize: function resize(file, width, height, resizeMethod) {
var info = {
srcX: 0,
srcY: 0,
srcWidth: file.width,
srcHeight: file.height,
};
var srcRatio = file.width / file.height;
if (width == null && height == null) {
width = info.srcWidth;
height = info.srcHeight;
} else if (width == null) {
width = height * srcRatio;
} else if (height == null) {
height = width / srcRatio;
}
width = Math.min(width, info.srcWidth);
height = Math.min(height, info.srcHeight);
var trgRatio = width / height;
if (info.srcWidth > width || info.srcHeight > height) {
if (resizeMethod === "crop") {
if (srcRatio > trgRatio) {
info.srcHeight = file.height;
info.srcWidth = info.srcHeight * trgRatio;
} else {
info.srcWidth = file.width;
info.srcHeight = info.srcWidth / trgRatio;
}
} else if (resizeMethod === "contain") {
if (srcRatio > trgRatio) {
height = width / srcRatio;
} else {
width = height * srcRatio;
}
} else {
throw new Error(
"Unknown resizeMethod '" +
resizeMethod +
"'"
);
}
}
info.srcX = (file.width - info.srcWidth) / 2;
info.srcY = (file.height - info.srcHeight) / 2;
info.trgWidth = width;
info.trgHeight = height;
return info;
},
transformFile: function transformFile(file, done) {
if (
(this.options.resizeWidth ||
this.options.resizeHeight) &&
file.type.match(/image.*/)
) {
return this.resizeImage(
file,
this.options.resizeWidth,
this.options.resizeHeight,
this.options.resizeMethod,
done
);
} else {
return done(file);
}
},
previewTemplate:
'<div class="dz-preview dz-file-preview">\n <div class="dz-image"><img data-dz-thumbnail /></div>\n <div class="dz-details">\n <div class="dz-size"><span data-dz-size></span></div>\n <div class="dz-filename"><span data-dz-name></span></div>\n </div>\n <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>\n <div class="dz-error-message"><span data-dz-errormessage></span></div>\n <div class="dz-success-mark">\n <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n <title>Check</title>\n <defs></defs>\n <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n <path d="M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" stroke-opacity="0.198794158" stroke="#747474" fill-opacity="0.816519475" fill="#FFFFFF" sketch:type="MSShapeGroup"></path>\n </g>\n </svg>\n </div>\n <div class="dz-error-mark">\n <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n <title>Error</title>\n <defs></defs>\n <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n <g id="Check-+-Oval-2" sketch:type="MSLayerGroup" stroke="#747474" stroke-opacity="0.198794158" fill="#FFFFFF" fill-opacity="0.816519475">\n <path d="M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" sketch:type="MSShapeGroup"></path>\n </g>\n </g>\n </svg>\n </div>\n</div>',
drop: function drop(e) {
return this.element.classList.remove("dz-drag-hover");
},
dragstart: function dragstart(e) {},
dragend: function dragend(e) {
return this.element.classList.remove("dz-drag-hover");
},
dragenter: function dragenter(e) {
return this.element.classList.add("dz-drag-hover");
},
dragover: function dragover(e) {
return this.element.classList.add("dz-drag-hover");
},
dragleave: function dragleave(e) {
return this.element.classList.remove("dz-drag-hover");
},
paste: function paste(e) {},
reset: function reset() {
return this.element.classList.remove("dz-started");
},
addedfile: function addedfile(file) {
var _this2 = this;
if (this.element === this.previewsContainer) {
this.element.classList.add("dz-started");
}
if (this.previewsContainer) {
file.previewElement = Dropzone.createElement(
this.options.previewTemplate.trim()
);
file.previewTemplate = file.previewElement;
this.previewsContainer.appendChild(
file.previewElement
);
for (
var _iterator3 = file.previewElement.querySelectorAll(
"[data-dz-name]"
),
_isArray3 = true,
_i3 = 0,
_iterator3 = _isArray3
? _iterator3
: _iterator3[Symbol.iterator]();
;
) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var node = _ref3;
node.textContent = file.name;
}
for (
var _iterator4 = file.previewElement.querySelectorAll(
"[data-dz-size]"
),
_isArray4 = true,
_i4 = 0,
_iterator4 = _isArray4
? _iterator4
: _iterator4[Symbol.iterator]();
;
) {
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
node = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
node = _i4.value;
}
node.innerHTML = this.filesize(file.size);
}
if (this.options.addRemoveLinks) {
file._removeLink = Dropzone.createElement(
'<a class="dz-remove" href="javascript:undefined;" data-dz-remove>' +
this.options.dictRemoveFile +
"</a>"
);
file.previewElement.appendChild(
file._removeLink
);
}
var removeFileEvent = function removeFileEvent(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(
_this2.options
.dictCancelUploadConfirmation,
function () {
return _this2.removeFile(file);
}
);
} else {
if (
_this2.options
.dictRemoveFileConfirmation
) {
return Dropzone.confirm(
_this2.options
.dictRemoveFileConfirmation,
function () {
return _this2.removeFile(file);
}
);
} else {
return _this2.removeFile(file);
}
}
};
for (
var _iterator5 = file.previewElement.querySelectorAll(
"[data-dz-remove]"
),
_isArray5 = true,
_i5 = 0,
_iterator5 = _isArray5
? _iterator5
: _iterator5[Symbol.iterator]();
;
) {
var _ref4;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref4 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref4 = _i5.value;
}
var removeLink = _ref4;
removeLink.addEventListener(
"click",
removeFileEvent
);
}
}
},
removedfile: function removedfile(file) {
if (
file.previewElement != null &&
file.previewElement.parentNode != null
) {
file.previewElement.parentNode.removeChild(
file.previewElement
);
}
return this._updateMaxFilesReachedClass();
},
thumbnail: function thumbnail(file, dataUrl) {
if (file.previewElement) {
file.previewElement.classList.remove(
"dz-file-preview"
);
for (
var _iterator6 = file.previewElement.querySelectorAll(
"[data-dz-thumbnail]"
),
_isArray6 = true,
_i6 = 0,
_iterator6 = _isArray6
? _iterator6
: _iterator6[Symbol.iterator]();
;
) {
var _ref5;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref5 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref5 = _i6.value;
}
var thumbnailElement = _ref5;
thumbnailElement.alt = file.name;
thumbnailElement.src = dataUrl;
}
return setTimeout(function () {
return file.previewElement.classList.add(
"dz-image-preview"
);
}, 1);
}
},
error: function error(file, message) {
if (file.previewElement) {
file.previewElement.classList.add("dz-error");
if (typeof message !== "String" && message.error) {
message = message.error;
}
for (
var _iterator7 = file.previewElement.querySelectorAll(
"[data-dz-errormessage]"
),
_isArray7 = true,
_i7 = 0,
_iterator7 = _isArray7
? _iterator7
: _iterator7[Symbol.iterator]();
;
) {
var _ref6;
if (_isArray7) {
if (_i7 >= _iterator7.length) break;
_ref6 = _iterator7[_i7++];
} else {
_i7 = _iterator7.next();
if (_i7.done) break;
_ref6 = _i7.value;
}
var node = _ref6;
node.textContent = message;
}
}
},
errormultiple: function errormultiple() {},
processing: function processing(file) {
if (file.previewElement) {
file.previewElement.classList.add("dz-processing");
if (file._removeLink) {
return (file._removeLink.innerHTML = this.options.dictCancelUpload);
}
}
},
processingmultiple: function processingmultiple() {},
uploadprogress: function uploadprogress(
file,
progress,
bytesSent
) {
if (file.previewElement) {
for (
var _iterator8 = file.previewElement.querySelectorAll(
"[data-dz-uploadprogress]"
),
_isArray8 = true,
_i8 = 0,
_iterator8 = _isArray8
? _iterator8
: _iterator8[Symbol.iterator]();
;
) {
var _ref7;
if (_isArray8) {
if (_i8 >= _iterator8.length) break;
_ref7 = _iterator8[_i8++];
} else {
_i8 = _iterator8.next();
if (_i8.done) break;
_ref7 = _i8.value;
}
var node = _ref7;
node.nodeName === "PROGRESS"
? (node.value = progress)
: (node.style.width = progress + "%");
}
}
},
totaluploadprogress: function totaluploadprogress() {},
sending: function sending() {},
sendingmultiple: function sendingmultiple() {},
success: function success(file) {
if (file.previewElement) {
return file.previewElement.classList.add(
"dz-success"
);
}
},
successmultiple: function successmultiple() {},
canceled: function canceled(file) {
return this.emit(
"error",
file,
this.options.dictUploadCanceled
);
},
canceledmultiple: function canceledmultiple() {},
complete: function complete(file) {
if (file._removeLink) {
file._removeLink.innerHTML = this.options.dictRemoveFile;
}
if (file.previewElement) {
return file.previewElement.classList.add(
"dz-complete"
);
}
},
completemultiple: function completemultiple() {},
maxfilesexceeded: function maxfilesexceeded() {},
maxfilesreached: function maxfilesreached() {},
queuecomplete: function queuecomplete() {},
addedfiles: function addedfiles() {},
};
this.prototype._thumbnailQueue = [];
this.prototype._processingThumbnail = false;
},
},
{
key: "extend",
value: function extend(target) {
for (
var _len2 = arguments.length,
objects = Array(_len2 > 1 ? _len2 - 1 : 0),
_key2 = 1;
_key2 < _len2;
_key2++
) {
objects[_key2 - 1] = arguments[_key2];
}
for (
var _iterator9 = objects,
_isArray9 = true,
_i9 = 0,
_iterator9 = _isArray9
? _iterator9
: _iterator9[Symbol.iterator]();
;
) {
var _ref8;
if (_isArray9) {
if (_i9 >= _iterator9.length) break;
_ref8 = _iterator9[_i9++];
} else {
_i9 = _iterator9.next();
if (_i9.done) break;
_ref8 = _i9.value;
}
var object = _ref8;
for (var key in object) {
var val = object[key];
target[key] = val;
}
}
return target;
},
},
]);
function Dropzone(el, options) {
_classCallCheck(this, Dropzone);
var _this = _possibleConstructorReturn(
this,
(Dropzone.__proto__ || Object.getPrototypeOf(Dropzone)).call(this)
);
var fallback = void 0,
left = void 0;
_this.element = el;
_this.version = Dropzone.version;
_this.defaultOptions.previewTemplate = _this.defaultOptions.previewTemplate.replace(
/\n*/g,
""
);
_this.clickableElements = [];
_this.listeners = [];
_this.files = [];
if (typeof _this.element === "string") {
_this.element = document.querySelector(_this.element);
}
if (!_this.element || _this.element.nodeType == null) {
throw new Error("Invalid dropzone element.");
}
if (_this.element.dropzone) {
throw new Error("Dropzone already attached.");
}
Dropzone.instances.push(_this);
_this.element.dropzone = _this;
var elementOptions =
(left = Dropzone.optionsForElement(_this.element)) != null
? left
: {};
_this.options = Dropzone.extend(
{},
_this.defaultOptions,
elementOptions,
options != null ? options : {}
);
if (_this.options.forceFallback || !Dropzone.isBrowserSupported()) {
var _ret;
return (
(_ret = _this.options.fallback.call(_this)),
_possibleConstructorReturn(_this, _ret)
);
}
if (_this.options.url == null) {
_this.options.url = _this.element.getAttribute("action");
}
if (!_this.options.url) {
throw new Error("No URL provided.");
}
if (_this.options.acceptedFiles && _this.options.acceptedMimeTypes) {
throw new Error(
"You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."
);
}
if (_this.options.uploadMultiple && _this.options.chunking) {
throw new Error(
"You cannot set both: uploadMultiple and chunking."
);
}
if (_this.options.acceptedMimeTypes) {
_this.options.acceptedFiles = _this.options.acceptedMimeTypes;
delete _this.options.acceptedMimeTypes;
}
if (_this.options.renameFilename != null) {
_this.options.renameFile = function (file) {
return _this.options.renameFilename.call(
_this,
file.name,
file
);
};
}
_this.options.method = _this.options.method.toUpperCase();
if ((fallback = _this.getExistingFallback()) && fallback.parentNode) {
fallback.parentNode.removeChild(fallback);
}
if (_this.options.previewsContainer !== false) {
if (_this.options.previewsContainer) {
_this.previewsContainer = Dropzone.getElement(
_this.options.previewsContainer,
"previewsContainer"
);
} else {
_this.previewsContainer = _this.element;
}
}
if (_this.options.clickable) {
if (_this.options.clickable === true) {
_this.clickableElements = [_this.element];
} else {
_this.clickableElements = Dropzone.getElements(
_this.options.clickable,
"clickable"
);
}
}
_this.init();
return _this;
}
_createClass(
Dropzone,
[
{
key: "getAcceptedFiles",
value: function getAcceptedFiles() {
return this.files
.filter(function (file) {
return file.accepted;
})
.map(function (file) {
return file;
});
},
},
{
key: "getRejectedFiles",
value: function getRejectedFiles() {
return this.files
.filter(function (file) {
return !file.accepted;
})
.map(function (file) {
return file;
});
},
},
{
key: "getFilesWithStatus",
value: function getFilesWithStatus(status) {
return this.files
.filter(function (file) {
return file.status === status;
})
.map(function (file) {
return file;
});
},
},
{
key: "getQueuedFiles",
value: function getQueuedFiles() {
return this.getFilesWithStatus(Dropzone.QUEUED);
},
},
{
key: "getUploadingFiles",
value: function getUploadingFiles() {
return this.getFilesWithStatus(Dropzone.UPLOADING);
},
},
{
key: "getAddedFiles",
value: function getAddedFiles() {
return this.getFilesWithStatus(Dropzone.ADDED);
},
},
{
key: "getActiveFiles",
value: function getActiveFiles() {
return this.files
.filter(function (file) {
return (
file.status === Dropzone.UPLOADING ||
file.status === Dropzone.QUEUED
);
})
.map(function (file) {
return file;
});
},
},
{
key: "init",
value: function init() {
var _this3 = this;
if (this.element.tagName === "form") {
this.element.setAttribute(
"enctype",
"multipart/form-data"
);
}
if (
this.element.classList.contains("dropzone") &&
!this.element.querySelector(".dz-message")
) {
this.element.appendChild(
Dropzone.createElement(
'<div class="dz-default dz-message"><span>' +
this.options.dictDefaultMessage +
"</span></div>"
)
);
}
if (this.clickableElements.length) {
var setupHiddenFileInput = function setupHiddenFileInput() {
if (_this3.hiddenFileInput) {
_this3.hiddenFileInput.parentNode.removeChild(
_this3.hiddenFileInput
);
}
_this3.hiddenFileInput = document.createElement(
"input"
);
_this3.hiddenFileInput.setAttribute("type", "file");
if (
_this3.options.maxFiles === null ||
_this3.options.maxFiles > 1
) {
_this3.hiddenFileInput.setAttribute(
"multiple",
"multiple"
);
}
_this3.hiddenFileInput.className =
"dz-hidden-input";
if (_this3.options.acceptedFiles !== null) {
_this3.hiddenFileInput.setAttribute(
"accept",
_this3.options.acceptedFiles
);
}
if (_this3.options.capture !== null) {
_this3.hiddenFileInput.setAttribute(
"capture",
_this3.options.capture
);
}
_this3.hiddenFileInput.style.visibility = "hidden";
_this3.hiddenFileInput.style.position = "absolute";
_this3.hiddenFileInput.style.top = "0";
_this3.hiddenFileInput.style.left = "0";
_this3.hiddenFileInput.style.height = "0";
_this3.hiddenFileInput.style.width = "0";
Dropzone.getElement(
_this3.options.hiddenInputContainer,
"hiddenInputContainer"
).appendChild(_this3.hiddenFileInput);
return _this3.hiddenFileInput.addEventListener(
"change",
function () {
var files = _this3.hiddenFileInput.files;
if (files.length) {
for (
var _iterator10 = files,
_isArray10 = true,
_i10 = 0,
_iterator10 = _isArray10
? _iterator10
: _iterator10[
Symbol.iterator
]();
;
) {
var _ref9;
if (_isArray10) {
if (_i10 >= _iterator10.length)
break;
_ref9 = _iterator10[_i10++];
} else {
_i10 = _iterator10.next();
if (_i10.done) break;
_ref9 = _i10.value;
}
var file = _ref9;
_this3.addFile(file);
}
}
_this3.emit("addedfiles", files);
return setupHiddenFileInput();
}
);
};
setupHiddenFileInput();
}
this.URL =
window.URL !== null ? window.URL : window.webkitURL;
for (
var _iterator11 = this.events,
_isArray11 = true,
_i11 = 0,
_iterator11 = _isArray11
? _iterator11
: _iterator11[Symbol.iterator]();
;
) {
var _ref10;
if (_isArray11) {
if (_i11 >= _iterator11.length) break;
_ref10 = _iterator11[_i11++];
} else {
_i11 = _iterator11.next();
if (_i11.done) break;
_ref10 = _i11.value;
}
var eventName = _ref10;
this.on(eventName, this.options[eventName]);
}
this.on("uploadprogress", function () {
return _this3.updateTotalUploadProgress();
});
this.on("removedfile", function () {
return _this3.updateTotalUploadProgress();
});
this.on("canceled", function (file) {
return _this3.emit("complete", file);
});
this.on("complete", function (file) {
if (
_this3.getAddedFiles().length === 0 &&
_this3.getUploadingFiles().length === 0 &&
_this3.getQueuedFiles().length === 0
) {
return setTimeout(function () {
return _this3.emit("queuecomplete");
}, 0);
}
});
var noPropagation = function noPropagation(e) {
e.stopPropagation();
if (e.preventDefault) {
return e.preventDefault();
} else {
return (e.returnValue = false);
}
};
this.listeners = [
{
element: this.element,
events: {
dragstart: function dragstart(e) {
return _this3.emit("dragstart", e);
},
dragenter: function dragenter(e) {
noPropagation(e);
return _this3.emit("dragenter", e);
},
dragover: function dragover(e) {
var efct = void 0;
try {
efct = e.dataTransfer.effectAllowed;
} catch (error) {}
e.dataTransfer.dropEffect =
"move" === efct || "linkMove" === efct
? "move"
: "copy";
noPropagation(e);
return _this3.emit("dragover", e);
},
dragleave: function dragleave(e) {
return _this3.emit("dragleave", e);
},
drop: function drop(e) {
noPropagation(e);
return _this3.drop(e);
},
dragend: function dragend(e) {
return _this3.emit("dragend", e);
},
},
},
];
this.clickableElements.forEach(function (clickableElement) {
return _this3.listeners.push({
element: clickableElement,
events: {
click: function click(evt) {
if (
clickableElement !== _this3.element ||
evt.target === _this3.element ||
Dropzone.elementInside(
evt.target,
_this3.element.querySelector(
".dz-message"
)
)
) {
_this3.hiddenFileInput.click();
}
return true;
},
},
});
});
this.enable();
return this.options.init.call(this);
},
},
{
key: "destroy",
value: function destroy() {
this.disable();
this.removeAllFiles(true);
if (
this.hiddenFileInput != null
? this.hiddenFileInput.parentNode
: undefined
) {
this.hiddenFileInput.parentNode.removeChild(
this.hiddenFileInput
);
this.hiddenFileInput = null;
}
delete this.element.dropzone;
return Dropzone.instances.splice(
Dropzone.instances.indexOf(this),
1
);
},
},
{
key: "updateTotalUploadProgress",
value: function updateTotalUploadProgress() {
var totalUploadProgress = void 0;
var totalBytesSent = 0;
var totalBytes = 0;
var activeFiles = this.getActiveFiles();
if (activeFiles.length) {
for (
var _iterator12 = this.getActiveFiles(),
_isArray12 = true,
_i12 = 0,
_iterator12 = _isArray12
? _iterator12
: _iterator12[Symbol.iterator]();
;
) {
var _ref11;
if (_isArray12) {
if (_i12 >= _iterator12.length) break;
_ref11 = _iterator12[_i12++];
} else {
_i12 = _iterator12.next();
if (_i12.done) break;
_ref11 = _i12.value;
}
var file = _ref11;
totalBytesSent += file.upload.bytesSent;
totalBytes += file.upload.total;
}
totalUploadProgress =
(100 * totalBytesSent) / totalBytes;
} else {
totalUploadProgress = 100;
}
return this.emit(
"totaluploadprogress",
totalUploadProgress,
totalBytes,
totalBytesSent
);
},
},
{
key: "_getParamName",
value: function _getParamName(n) {
if (typeof this.options.paramName === "function") {
return this.options.paramName(n);
} else {
return (
"" +
this.options.paramName +
(this.options.uploadMultiple ? "[" + n + "]" : "")
);
}
},
},
{
key: "_renameFile",
value: function _renameFile(file) {
if (typeof this.options.renameFile !== "function") {
return file.name;
}
return this.options.renameFile(file);
},
},
{
key: "getFallbackForm",
value: function getFallbackForm() {
var existingFallback = void 0,
form = void 0;
if ((existingFallback = this.getExistingFallback())) {
return existingFallback;
}
var fieldsString = '<div class="dz-fallback">';
if (this.options.dictFallbackText) {
fieldsString +=
"<p>" + this.options.dictFallbackText + "</p>";
}
fieldsString +=
'<input type="file" name="' +
this._getParamName(0) +
'" ' +
(this.options.uploadMultiple
? 'multiple="multiple"'
: undefined) +
' /><input type="submit" value="Upload!"></div>';
var fields = Dropzone.createElement(fieldsString);
if (this.element.tagName !== "FORM") {
form = Dropzone.createElement(
'<form action="' +
this.options.url +
'" enctype="multipart/form-data" method="' +
this.options.method +
'"></form>'
);
form.appendChild(fields);
} else {
this.element.setAttribute(
"enctype",
"multipart/form-data"
);
this.element.setAttribute(
"method",
this.options.method
);
}
return form != null ? form : fields;
},
},
{
key: "getExistingFallback",
value: function getExistingFallback() {
var getFallback = function getFallback(elements) {
for (
var _iterator13 = elements,
_isArray13 = true,
_i13 = 0,
_iterator13 = _isArray13
? _iterator13
: _iterator13[Symbol.iterator]();
;
) {
var _ref12;
if (_isArray13) {
if (_i13 >= _iterator13.length) break;
_ref12 = _iterator13[_i13++];
} else {
_i13 = _iterator13.next();
if (_i13.done) break;
_ref12 = _i13.value;
}
var el = _ref12;
if (/(^| )fallback($| )/.test(el.className)) {
return el;
}
}
};
var _arr = ["div", "form"];
for (var _i14 = 0; _i14 < _arr.length; _i14++) {
var tagName = _arr[_i14];
var fallback;
if (
(fallback = getFallback(
this.element.getElementsByTagName(tagName)
))
) {
return fallback;
}
}
},
},
{
key: "setupEventListeners",
value: function setupEventListeners() {
return this.listeners.map(function (elementListeners) {
return (function () {
var result = [];
for (var event in elementListeners.events) {
var listener = elementListeners.events[event];
result.push(
elementListeners.element.addEventListener(
event,
listener,
false
)
);
}
return result;
})();
});
},
},
{
key: "removeEventListeners",
value: function removeEventListeners() {
return this.listeners.map(function (elementListeners) {
return (function () {
var result = [];
for (var event in elementListeners.events) {
var listener = elementListeners.events[event];
result.push(
elementListeners.element.removeEventListener(
event,
listener,
false
)
);
}
return result;
})();
});
},
},
{
key: "disable",
value: function disable() {
var _this4 = this;
this.clickableElements.forEach(function (element) {
return element.classList.remove("dz-clickable");
});
this.removeEventListeners();
this.disabled = true;
return this.files.map(function (file) {
return _this4.cancelUpload(file);
});
},
},
{
key: "enable",
value: function enable() {
delete this.disabled;
this.clickableElements.forEach(function (element) {
return element.classList.add("dz-clickable");
});
return this.setupEventListeners();
},
},
{
key: "filesize",
value: function filesize(size) {
var selectedSize = 0;
var selectedUnit = "b";
if (size > 0) {
var units = ["tb", "gb", "mb", "kb", "b"];
for (var i = 0; i < units.length; i++) {
var unit = units[i];
var cutoff =
Math.pow(this.options.filesizeBase, 4 - i) / 10;
if (size >= cutoff) {
selectedSize =
size /
Math.pow(this.options.filesizeBase, 4 - i);
selectedUnit = unit;
break;
}
}
selectedSize = Math.round(10 * selectedSize) / 10;
}
return (
"<strong>" +
selectedSize +
"</strong> " +
this.options.dictFileSizeUnits[selectedUnit]
);
},
},
{
key: "_updateMaxFilesReachedClass",
value: function _updateMaxFilesReachedClass() {
if (
this.options.maxFiles != null &&
this.getAcceptedFiles().length >= this.options.maxFiles
) {
if (
this.getAcceptedFiles().length ===
this.options.maxFiles
) {
this.emit("maxfilesreached", this.files);
}
return this.element.classList.add(
"dz-max-files-reached"
);
} else {
return this.element.classList.remove(
"dz-max-files-reached"
);
}
},
},
{
key: "drop",
value: function drop(e) {
if (!e.dataTransfer) {
return;
}
this.emit("drop", e);
var files = [];
for (var i = 0; i < e.dataTransfer.files.length; i++) {
files[i] = e.dataTransfer.files[i];
}
this.emit("addedfiles", files);
if (files.length) {
var items = e.dataTransfer.items;
if (
items &&
items.length &&
items[0].webkitGetAsEntry != null
) {
this._addFilesFromItems(items);
} else {
this.handleFiles(files);
}
}
},
},
{
key: "paste",
value: function paste(e) {
if (
__guard__(
e != null ? e.clipboardData : undefined,
function (x) {
return x.items;
}
) == null
) {
return;
}
this.emit("paste", e);
var items = e.clipboardData.items;
if (items.length) {
return this._addFilesFromItems(items);
}
},
},
{
key: "handleFiles",
value: function handleFiles(files) {
for (
var _iterator14 = files,
_isArray14 = true,
_i15 = 0,
_iterator14 = _isArray14
? _iterator14
: _iterator14[Symbol.iterator]();
;
) {
var _ref13;
if (_isArray14) {
if (_i15 >= _iterator14.length) break;
_ref13 = _iterator14[_i15++];
} else {
_i15 = _iterator14.next();
if (_i15.done) break;
_ref13 = _i15.value;
}
var file = _ref13;
this.addFile(file);
}
},
},
{
key: "_addFilesFromItems",
value: function _addFilesFromItems(items) {
var _this5 = this;
return (function () {
var result = [];
for (
var _iterator15 = items,
_isArray15 = true,
_i16 = 0,
_iterator15 = _isArray15
? _iterator15
: _iterator15[Symbol.iterator]();
;
) {
var _ref14;
if (_isArray15) {
if (_i16 >= _iterator15.length) break;
_ref14 = _iterator15[_i16++];
} else {
_i16 = _iterator15.next();
if (_i16.done) break;
_ref14 = _i16.value;
}
var item = _ref14;
var entry;
if (
item.webkitGetAsEntry != null &&
(entry = item.webkitGetAsEntry())
) {
if (entry.isFile) {
result.push(
_this5.addFile(item.getAsFile())
);
} else if (entry.isDirectory) {
result.push(
_this5._addFilesFromDirectory(
entry,
entry.name
)
);
} else {
result.push(undefined);
}
} else if (item.getAsFile != null) {
if (item.kind == null || item.kind === "file") {
result.push(
_this5.addFile(item.getAsFile())
);
} else {
result.push(undefined);
}
} else {
result.push(undefined);
}
}
return result;
})();
},
},
{
key: "_addFilesFromDirectory",
value: function _addFilesFromDirectory(directory, path) {
var _this6 = this;
var dirReader = directory.createReader();
var errorHandler = function errorHandler(error) {
return __guardMethod__(console, "log", function (o) {
return o.log(error);
});
};
var readEntries = function readEntries() {
return dirReader.readEntries(function (entries) {
if (entries.length > 0) {
for (
var _iterator16 = entries,
_isArray16 = true,
_i17 = 0,
_iterator16 = _isArray16
? _iterator16
: _iterator16[Symbol.iterator]();
;
) {
var _ref15;
if (_isArray16) {
if (_i17 >= _iterator16.length) break;
_ref15 = _iterator16[_i17++];
} else {
_i17 = _iterator16.next();
if (_i17.done) break;
_ref15 = _i17.value;
}
var entry = _ref15;
if (entry.isFile) {
entry.file(function (file) {
if (
_this6.options
.ignoreHiddenFiles &&
file.name.substring(0, 1) ===
"."
) {
return;
}
file.fullPath =
path + "/" + file.name;
return _this6.addFile(file);
});
} else if (entry.isDirectory) {
_this6._addFilesFromDirectory(
entry,
path + "/" + entry.name
);
}
}
readEntries();
}
return null;
}, errorHandler);
};
return readEntries();
},
},
{
key: "accept",
value: function accept(file, done) {
if (
this.options.maxFilesize &&
file.size > this.options.maxFilesize * 1024 * 1024
) {
return done(
this.options.dictFileTooBig
.replace(
"{{filesize}}",
Math.round(file.size / 1024 / 10.24) / 100
)
.replace(
"{{maxFilesize}}",
this.options.maxFilesize
)
);
} else if (
!Dropzone.isValidFile(file, this.options.acceptedFiles)
) {
return done(this.options.dictInvalidFileType);
} else if (
this.options.maxFiles != null &&
this.getAcceptedFiles().length >= this.options.maxFiles
) {
done(
this.options.dictMaxFilesExceeded.replace(
"{{maxFiles}}",
this.options.maxFiles
)
);
return this.emit("maxfilesexceeded", file);
} else {
return this.options.accept.call(this, file, done);
}
},
},
{
key: "addFile",
value: function addFile(file) {
var _this7 = this;
file.upload = {
uuid: Dropzone.uuidv4(),
progress: 0,
total: file.size,
bytesSent: 0,
filename: this._renameFile(file),
chunked:
this.options.chunking &&
(this.options.forceChunking ||
file.size > this.options.chunkSize),
totalChunkCount: Math.ceil(
file.size / this.options.chunkSize
),
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, function (error) {
if (error) {
file.accepted = false;
_this7._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this7.options.autoQueue) {
_this7.enqueueFile(file);
}
}
return _this7._updateMaxFilesReachedClass();
});
},
},
{
key: "enqueueFiles",
value: function enqueueFiles(files) {
for (
var _iterator17 = files,
_isArray17 = true,
_i18 = 0,
_iterator17 = _isArray17
? _iterator17
: _iterator17[Symbol.iterator]();
;
) {
var _ref16;
if (_isArray17) {
if (_i18 >= _iterator17.length) break;
_ref16 = _iterator17[_i18++];
} else {
_i18 = _iterator17.next();
if (_i18.done) break;
_ref16 = _i18.value;
}
var file = _ref16;
this.enqueueFile(file);
}
return null;
},
},
{
key: "enqueueFile",
value: function enqueueFile(file) {
var _this8 = this;
if (
file.status === Dropzone.ADDED &&
file.accepted === true
) {
file.status = Dropzone.QUEUED;
if (this.options.autoProcessQueue) {
return setTimeout(function () {
return _this8.processQueue();
}, 0);
}
} else {
throw new Error(
"This file can't be queued because it has already been processed or was rejected."
);
}
},
},
{
key: "_enqueueThumbnail",
value: function _enqueueThumbnail(file) {
var _this9 = this;
if (
this.options.createImageThumbnails &&
file.type.match(/image.*/) &&
file.size <=
this.options.maxThumbnailFilesize * 1024 * 1024
) {
this._thumbnailQueue.push(file);
return setTimeout(function () {
return _this9._processThumbnailQueue();
}, 0);
}
},
},
{
key: "_processThumbnailQueue",
value: function _processThumbnailQueue() {
var _this10 = this;
if (
this._processingThumbnail ||
this._thumbnailQueue.length === 0
) {
return;
}
this._processingThumbnail = true;
var file = this._thumbnailQueue.shift();
return this.createThumbnail(
file,
this.options.thumbnailWidth,
this.options.thumbnailHeight,
this.options.thumbnailMethod,
true,
function (dataUrl) {
_this10.emit("thumbnail", file, dataUrl);
_this10._processingThumbnail = false;
return _this10._processThumbnailQueue();
}
);
},
},
{
key: "removeFile",
value: function removeFile(file) {
if (file.status === Dropzone.UPLOADING) {
this.cancelUpload(file);
}
this.files = without(this.files, file);
this.emit("removedfile", file);
if (this.files.length === 0) {
return this.emit("reset");
}
},
},
{
key: "removeAllFiles",
value: function removeAllFiles(cancelIfNecessary) {
if (cancelIfNecessary == null) {
cancelIfNecessary = false;
}
for (
var _iterator18 = this.files.slice(),
_isArray18 = true,
_i19 = 0,
_iterator18 = _isArray18
? _iterator18
: _iterator18[Symbol.iterator]();
;
) {
var _ref17;
if (_isArray18) {
if (_i19 >= _iterator18.length) break;
_ref17 = _iterator18[_i19++];
} else {
_i19 = _iterator18.next();
if (_i19.done) break;
_ref17 = _i19.value;
}
var file = _ref17;
if (
file.status !== Dropzone.UPLOADING ||
cancelIfNecessary
) {
this.removeFile(file);
}
}
return null;
},
},
{
key: "resizeImage",
value: function resizeImage(
file,
width,
height,
resizeMethod,
callback
) {
var _this11 = this;
return this.createThumbnail(
file,
width,
height,
resizeMethod,
true,
function (dataUrl, canvas) {
if (canvas == null) {
return callback(file);
} else {
var resizeMimeType =
_this11.options.resizeMimeType;
if (resizeMimeType == null) {
resizeMimeType = file.type;
}
var resizedDataURL = canvas.toDataURL(
resizeMimeType,
_this11.options.resizeQuality
);
if (
resizeMimeType === "image/jpeg" ||
resizeMimeType === "image/jpg"
) {
resizedDataURL = ExifRestore.restore(
file.dataURL,
resizedDataURL
);
}
return callback(
Dropzone.dataURItoBlob(resizedDataURL)
);
}
}
);
},
},
{
key: "createThumbnail",
value: function createThumbnail(
file,
width,
height,
resizeMethod,
fixOrientation,
callback
) {
var _this12 = this;
var fileReader = new FileReader();
fileReader.onload = function () {
file.dataURL = fileReader.result;
if (file.type === "image/svg+xml") {
if (callback != null) {
callback(fileReader.result);
}
return;
}
return _this12.createThumbnailFromUrl(
file,
width,
height,
resizeMethod,
fixOrientation,
callback
);
};
return fileReader.readAsDataURL(file);
},
},
{
key: "createThumbnailFromUrl",
value: function createThumbnailFromUrl(
file,
width,
height,
resizeMethod,
fixOrientation,
callback,
crossOrigin
) {
var _this13 = this;
var img = document.createElement("img");
if (crossOrigin) {
img.crossOrigin = crossOrigin;
}
img.onload = function () {
var loadExif = function loadExif(callback) {
return callback(1);
};
if (
typeof EXIF !== "undefined" &&
EXIF !== null &&
fixOrientation
) {
loadExif = function loadExif(callback) {
return EXIF.getData(img, function () {
return callback(
EXIF.getTag(this, "Orientation")
);
});
};
}
return loadExif(function (orientation) {
file.width = img.width;
file.height = img.height;
var resizeInfo = _this13.options.resize.call(
_this13,
file,
width,
height,
resizeMethod
);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = resizeInfo.trgWidth;
canvas.height = resizeInfo.trgHeight;
if (orientation > 4) {
canvas.width = resizeInfo.trgHeight;
canvas.height = resizeInfo.trgWidth;
}
switch (orientation) {
case 2:
ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);
break;
case 3:
ctx.translate(canvas.width, canvas.height);
ctx.rotate(Math.PI);
break;
case 4:
ctx.translate(0, canvas.height);
ctx.scale(1, -1);
break;
case 5:
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -canvas.width);
break;
case 7:
ctx.rotate(0.5 * Math.PI);
ctx.translate(canvas.height, -canvas.width);
ctx.scale(-1, 1);
break;
case 8:
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-canvas.height, 0);
break;
}
drawImageIOSFix(
ctx,
img,
resizeInfo.srcX != null ? resizeInfo.srcX : 0,
resizeInfo.srcY != null ? resizeInfo.srcY : 0,
resizeInfo.srcWidth,
resizeInfo.srcHeight,
resizeInfo.trgX != null ? resizeInfo.trgX : 0,
resizeInfo.trgY != null ? resizeInfo.trgY : 0,
resizeInfo.trgWidth,
resizeInfo.trgHeight
);
var thumbnail = canvas.toDataURL("image/png");
if (callback != null) {
return callback(thumbnail, canvas);
}
});
};
if (callback != null) {
img.onerror = callback;
}
return (img.src = file.dataURL);
},
},
{
key: "processQueue",
value: function processQueue() {
var parallelUploads = this.options.parallelUploads;
var processingLength = this.getUploadingFiles().length;
var i = processingLength;
if (processingLength >= parallelUploads) {
return;
}
var queuedFiles = this.getQueuedFiles();
if (!(queuedFiles.length > 0)) {
return;
}
if (this.options.uploadMultiple) {
return this.processFiles(
queuedFiles.slice(
0,
parallelUploads - processingLength
)
);
} else {
while (i < parallelUploads) {
if (!queuedFiles.length) {
return;
}
this.processFile(queuedFiles.shift());
i++;
}
}
},
},
{
key: "processFile",
value: function processFile(file) {
return this.processFiles([file]);
},
},
{
key: "processFiles",
value: function processFiles(files) {
for (
var _iterator19 = files,
_isArray19 = true,
_i20 = 0,
_iterator19 = _isArray19
? _iterator19
: _iterator19[Symbol.iterator]();
;
) {
var _ref18;
if (_isArray19) {
if (_i20 >= _iterator19.length) break;
_ref18 = _iterator19[_i20++];
} else {
_i20 = _iterator19.next();
if (_i20.done) break;
_ref18 = _i20.value;
}
var file = _ref18;
file.processing = true;
file.status = Dropzone.UPLOADING;
this.emit("processing", file);
}
if (this.options.uploadMultiple) {
this.emit("processingmultiple", files);
}
return this.uploadFiles(files);
},
},
{
key: "_getFilesWithXhr",
value: function _getFilesWithXhr(xhr) {
var files = void 0;
return (files = this.files
.filter(function (file) {
return file.xhr === xhr;
})
.map(function (file) {
return file;
}));
},
},
{
key: "cancelUpload",
value: function cancelUpload(file) {
if (file.status === Dropzone.UPLOADING) {
var groupedFiles = this._getFilesWithXhr(file.xhr);
for (
var _iterator20 = groupedFiles,
_isArray20 = true,
_i21 = 0,
_iterator20 = _isArray20
? _iterator20
: _iterator20[Symbol.iterator]();
;
) {
var _ref19;
if (_isArray20) {
if (_i21 >= _iterator20.length) break;
_ref19 = _iterator20[_i21++];
} else {
_i21 = _iterator20.next();
if (_i21.done) break;
_ref19 = _i21.value;
}
var groupedFile = _ref19;
groupedFile.status = Dropzone.CANCELED;
}
if (typeof file.xhr !== "undefined") {
file.xhr.abort();
}
for (
var _iterator21 = groupedFiles,
_isArray21 = true,
_i22 = 0,
_iterator21 = _isArray21
? _iterator21
: _iterator21[Symbol.iterator]();
;
) {
var _ref20;
if (_isArray21) {
if (_i22 >= _iterator21.length) break;
_ref20 = _iterator21[_i22++];
} else {
_i22 = _iterator21.next();
if (_i22.done) break;
_ref20 = _i22.value;
}
var _groupedFile = _ref20;
this.emit("canceled", _groupedFile);
}
if (this.options.uploadMultiple) {
this.emit("canceledmultiple", groupedFiles);
}
} else if (
file.status === Dropzone.ADDED ||
file.status === Dropzone.QUEUED
) {
file.status = Dropzone.CANCELED;
this.emit("canceled", file);
if (this.options.uploadMultiple) {
this.emit("canceledmultiple", [file]);
}
}
if (this.options.autoProcessQueue) {
return this.processQueue();
}
},
},
{
key: "resolveOption",
value: function resolveOption(option) {
if (typeof option === "function") {
for (
var _len3 = arguments.length,
args = Array(_len3 > 1 ? _len3 - 1 : 0),
_key3 = 1;
_key3 < _len3;
_key3++
) {
args[_key3 - 1] = arguments[_key3];
}
return option.apply(this, args);
}
return option;
},
},
{
key: "uploadFile",
value: function uploadFile(file) {
return this.uploadFiles([file]);
},
},
{
key: "uploadFiles",
value: function uploadFiles(files) {
var _this14 = this;
this._transformFiles(files, function (transformedFiles) {
if (files[0].upload.chunked) {
var file = files[0];
var transformedFile = transformedFiles[0];
var startedChunkCount = 0;
file.upload.chunks = [];
var handleNextChunk = function handleNextChunk() {
var chunkIndex = 0;
while (
file.upload.chunks[chunkIndex] !== undefined
) {
chunkIndex++;
}
if (chunkIndex >= file.upload.totalChunkCount)
return;
startedChunkCount++;
var start =
chunkIndex * _this14.options.chunkSize;
var end = Math.min(
start + _this14.options.chunkSize,
file.size
);
var dataBlock = {
name: _this14._getParamName(0),
data: transformedFile.webkitSlice
? transformedFile.webkitSlice(
start,
end
)
: transformedFile.slice(start, end),
filename: file.upload.filename,
chunkIndex: chunkIndex,
};
file.upload.chunks[chunkIndex] = {
file: file,
index: chunkIndex,
dataBlock: dataBlock,
status: Dropzone.UPLOADING,
progress: 0,
retries: 0,
};
_this14._uploadData(files, [dataBlock]);
};
file.upload.finishedChunkUpload = function (chunk) {
var allFinished = true;
chunk.status = Dropzone.SUCCESS;
chunk.dataBlock = null;
chunk.xhr = null;
for (
var i = 0;
i < file.upload.totalChunkCount;
i++
) {
if (file.upload.chunks[i] === undefined) {
return handleNextChunk();
}
if (
file.upload.chunks[i].status !==
Dropzone.SUCCESS
) {
allFinished = false;
}
}
if (allFinished) {
_this14.options.chunksUploaded(
file,
function () {
_this14._finished(files, "", null);
}
);
}
};
if (_this14.options.parallelChunkUploads) {
for (
var i = 0;
i < file.upload.totalChunkCount;
i++
) {
handleNextChunk();
}
} else {
handleNextChunk();
}
} else {
var dataBlocks = [];
for (var _i23 = 0; _i23 < files.length; _i23++) {
dataBlocks[_i23] = {
name: _this14._getParamName(_i23),
data: transformedFiles[_i23],
filename: files[_i23].upload.filename,
};
}
_this14._uploadData(files, dataBlocks);
}
});
},
},
{
key: "_getChunk",
value: function _getChunk(file, xhr) {
for (var i = 0; i < file.upload.totalChunkCount; i++) {
if (
file.upload.chunks[i] !== undefined &&
file.upload.chunks[i].xhr === xhr
) {
return file.upload.chunks[i];
}
}
},
},
{
key: "_uploadData",
value: function _uploadData(files, dataBlocks) {
var _this15 = this;
var xhr = new XMLHttpRequest();
for (
var _iterator22 = files,
_isArray22 = true,
_i24 = 0,
_iterator22 = _isArray22
? _iterator22
: _iterator22[Symbol.iterator]();
;
) {
var _ref21;
if (_isArray22) {
if (_i24 >= _iterator22.length) break;
_ref21 = _iterator22[_i24++];
} else {
_i24 = _iterator22.next();
if (_i24.done) break;
_ref21 = _i24.value;
}
var file = _ref21;
file.xhr = xhr;
}
if (files[0].upload.chunked) {
files[0].upload.chunks[
dataBlocks[0].chunkIndex
].xhr = xhr;
}
var method = this.resolveOption(this.options.method, files);
var url = this.resolveOption(this.options.url, files);
xhr.open(method, url, true);
xhr.timeout = this.resolveOption(
this.options.timeout,
files
);
xhr.withCredentials = !!this.options.withCredentials;
xhr.onload = function (e) {
_this15._finishedUploading(files, xhr, e);
};
xhr.onerror = function () {
_this15._handleUploadError(files, xhr);
};
var progressObj = xhr.upload != null ? xhr.upload : xhr;
progressObj.onprogress = function (e) {
return _this15._updateFilesUploadProgress(
files,
xhr,
e
);
};
var headers = {
Accept: "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest",
};
if (this.options.headers) {
Dropzone.extend(headers, this.options.headers);
}
for (var headerName in headers) {
var headerValue = headers[headerName];
if (headerValue) {
xhr.setRequestHeader(headerName, headerValue);
}
}
var formData = new FormData();
if (this.options.params) {
var additionalParams = this.options.params;
if (typeof additionalParams === "function") {
additionalParams = additionalParams.call(
this,
files,
xhr,
files[0].upload.chunked
? this._getChunk(files[0], xhr)
: null
);
}
for (var key in additionalParams) {
var value = additionalParams[key];
formData.append(key, value);
}
}
for (
var _iterator23 = files,
_isArray23 = true,
_i25 = 0,
_iterator23 = _isArray23
? _iterator23
: _iterator23[Symbol.iterator]();
;
) {
var _ref22;
if (_isArray23) {
if (_i25 >= _iterator23.length) break;
_ref22 = _iterator23[_i25++];
} else {
_i25 = _iterator23.next();
if (_i25.done) break;
_ref22 = _i25.value;
}
var _file = _ref22;
this.emit("sending", _file, xhr, formData);
}
if (this.options.uploadMultiple) {
this.emit("sendingmultiple", files, xhr, formData);
}
this._addFormElementData(formData);
for (var i = 0; i < dataBlocks.length; i++) {
var dataBlock = dataBlocks[i];
formData.append(
dataBlock.name,
dataBlock.data,
dataBlock.filename
);
}
this.submitRequest(xhr, formData, files);
},
},
{
key: "_transformFiles",
value: function _transformFiles(files, done) {
var _this16 = this;
var transformedFiles = [];
var doneCounter = 0;
var _loop = function _loop(i) {
_this16.options.transformFile.call(
_this16,
files[i],
function (transformedFile) {
transformedFiles[i] = transformedFile;
if (++doneCounter === files.length) {
done(transformedFiles);
}
}
);
};
for (var i = 0; i < files.length; i++) {
_loop(i);
}
},
},
{
key: "_addFormElementData",
value: function _addFormElementData(formData) {
if (this.element.tagName === "FORM") {
for (
var _iterator24 = this.element.querySelectorAll(
"input, textarea, select, button"
),
_isArray24 = true,
_i26 = 0,
_iterator24 = _isArray24
? _iterator24
: _iterator24[Symbol.iterator]();
;
) {
var _ref23;
if (_isArray24) {
if (_i26 >= _iterator24.length) break;
_ref23 = _iterator24[_i26++];
} else {
_i26 = _iterator24.next();
if (_i26.done) break;
_ref23 = _i26.value;
}
var input = _ref23;
var inputName = input.getAttribute("name");
var inputType = input.getAttribute("type");
if (inputType) inputType = inputType.toLowerCase();
if (
typeof inputName === "undefined" ||
inputName === null
)
continue;
if (
input.tagName === "SELECT" &&
input.hasAttribute("multiple")
) {
for (
var _iterator25 = input.options,
_isArray25 = true,
_i27 = 0,
_iterator25 = _isArray25
? _iterator25
: _iterator25[Symbol.iterator]();
;
) {
var _ref24;
if (_isArray25) {
if (_i27 >= _iterator25.length) break;
_ref24 = _iterator25[_i27++];
} else {
_i27 = _iterator25.next();
if (_i27.done) break;
_ref24 = _i27.value;
}
var option = _ref24;
if (option.selected) {
formData.append(
inputName,
option.value
);
}
}
} else if (
!inputType ||
(inputType !== "checkbox" &&
inputType !== "radio") ||
input.checked
) {
formData.append(inputName, input.value);
}
}
}
},
},
{
key: "_updateFilesUploadProgress",
value: function _updateFilesUploadProgress(files, xhr, e) {
var progress = void 0;
if (typeof e !== "undefined") {
progress = (100 * e.loaded) / e.total;
if (files[0].upload.chunked) {
var file = files[0];
var chunk = this._getChunk(file, xhr);
chunk.progress = progress;
chunk.total = e.total;
chunk.bytesSent = e.loaded;
var fileProgress = 0,
fileTotal = void 0,
fileBytesSent = void 0;
file.upload.progress = 0;
file.upload.total = 0;
file.upload.bytesSent = 0;
for (
var i = 0;
i < file.upload.totalChunkCount;
i++
) {
if (
file.upload.chunks[i] !== undefined &&
file.upload.chunks[i].progress !== undefined
) {
file.upload.progress +=
file.upload.chunks[i].progress;
file.upload.total +=
file.upload.chunks[i].total;
file.upload.bytesSent +=
file.upload.chunks[i].bytesSent;
}
}
file.upload.progress =
file.upload.progress /
file.upload.totalChunkCount;
} else {
for (
var _iterator26 = files,
_isArray26 = true,
_i28 = 0,
_iterator26 = _isArray26
? _iterator26
: _iterator26[Symbol.iterator]();
;
) {
var _ref25;
if (_isArray26) {
if (_i28 >= _iterator26.length) break;
_ref25 = _iterator26[_i28++];
} else {
_i28 = _iterator26.next();
if (_i28.done) break;
_ref25 = _i28.value;
}
var _file2 = _ref25;
_file2.upload.progress = progress;
_file2.upload.total = e.total;
_file2.upload.bytesSent = e.loaded;
}
}
for (
var _iterator27 = files,
_isArray27 = true,
_i29 = 0,
_iterator27 = _isArray27
? _iterator27
: _iterator27[Symbol.iterator]();
;
) {
var _ref26;
if (_isArray27) {
if (_i29 >= _iterator27.length) break;
_ref26 = _iterator27[_i29++];
} else {
_i29 = _iterator27.next();
if (_i29.done) break;
_ref26 = _i29.value;
}
var _file3 = _ref26;
this.emit(
"uploadprogress",
_file3,
_file3.upload.progress,
_file3.upload.bytesSent
);
}
} else {
var allFilesFinished = true;
progress = 100;
for (
var _iterator28 = files,
_isArray28 = true,
_i30 = 0,
_iterator28 = _isArray28
? _iterator28
: _iterator28[Symbol.iterator]();
;
) {
var _ref27;
if (_isArray28) {
if (_i30 >= _iterator28.length) break;
_ref27 = _iterator28[_i30++];
} else {
_i30 = _iterator28.next();
if (_i30.done) break;
_ref27 = _i30.value;
}
var _file4 = _ref27;
if (
_file4.upload.progress !== 100 ||
_file4.upload.bytesSent !== _file4.upload.total
) {
allFilesFinished = false;
}
_file4.upload.progress = progress;
_file4.upload.bytesSent = _file4.upload.total;
}
if (allFilesFinished) {
return;
}
for (
var _iterator29 = files,
_isArray29 = true,
_i31 = 0,
_iterator29 = _isArray29
? _iterator29
: _iterator29[Symbol.iterator]();
;
) {
var _ref28;
if (_isArray29) {
if (_i31 >= _iterator29.length) break;
_ref28 = _iterator29[_i31++];
} else {
_i31 = _iterator29.next();
if (_i31.done) break;
_ref28 = _i31.value;
}
var _file5 = _ref28;
this.emit(
"uploadprogress",
_file5,
progress,
_file5.upload.bytesSent
);
}
}
},
},
{
key: "_finishedUploading",
value: function _finishedUploading(files, xhr, e) {
var response = void 0;
if (files[0].status === Dropzone.CANCELED) {
return;
}
if (xhr.readyState !== 4) {
return;
}
if (
xhr.responseType !== "arraybuffer" &&
xhr.responseType !== "blob"
) {
response = xhr.responseText;
if (
xhr.getResponseHeader("content-type") &&
~xhr
.getResponseHeader("content-type")
.indexOf("application/json")
) {
try {
response = JSON.parse(response);
} catch (error) {
e = error;
response = "Invalid JSON response from server.";
}
}
}
this._updateFilesUploadProgress(files);
if (!(200 <= xhr.status && xhr.status < 300)) {
this._handleUploadError(files, xhr, response);
} else {
if (files[0].upload.chunked) {
files[0].upload.finishedChunkUpload(
this._getChunk(files[0], xhr)
);
} else {
this._finished(files, response, e);
}
}
},
},
{
key: "_handleUploadError",
value: function _handleUploadError(files, xhr, response) {
if (files[0].status === Dropzone.CANCELED) {
return;
}
if (files[0].upload.chunked && this.options.retryChunks) {
var chunk = this._getChunk(files[0], xhr);
if (chunk.retries++ < this.options.retryChunksLimit) {
this._uploadData(files, [chunk.dataBlock]);
return;
} else {
console.warn(
"Retried this chunk too often. Giving up."
);
}
}
for (
var _iterator30 = files,
_isArray30 = true,
_i32 = 0,
_iterator30 = _isArray30
? _iterator30
: _iterator30[Symbol.iterator]();
;
) {
var _ref29;
if (_isArray30) {
if (_i32 >= _iterator30.length) break;
_ref29 = _iterator30[_i32++];
} else {
_i32 = _iterator30.next();
if (_i32.done) break;
_ref29 = _i32.value;
}
var file = _ref29;
this._errorProcessing(
files,
response ||
this.options.dictResponseError.replace(
"{{statusCode}}",
xhr.status
),
xhr
);
}
},
},
{
key: "submitRequest",
value: function submitRequest(xhr, formData, files) {
xhr.send(formData);
},
},
{
key: "_finished",
value: function _finished(files, responseText, e) {
for (
var _iterator31 = files,
_isArray31 = true,
_i33 = 0,
_iterator31 = _isArray31
? _iterator31
: _iterator31[Symbol.iterator]();
;
) {
var _ref30;
if (_isArray31) {
if (_i33 >= _iterator31.length) break;
_ref30 = _iterator31[_i33++];
} else {
_i33 = _iterator31.next();
if (_i33.done) break;
_ref30 = _i33.value;
}
var file = _ref30;
file.status = Dropzone.SUCCESS;
this.emit("success", file, responseText, e);
this.emit("complete", file);
}
if (this.options.uploadMultiple) {
this.emit("successmultiple", files, responseText, e);
this.emit("completemultiple", files);
}
if (this.options.autoProcessQueue) {
return this.processQueue();
}
},
},
{
key: "_errorProcessing",
value: function _errorProcessing(files, message, xhr) {
for (
var _iterator32 = files,
_isArray32 = true,
_i34 = 0,
_iterator32 = _isArray32
? _iterator32
: _iterator32[Symbol.iterator]();
;
) {
var _ref31;
if (_isArray32) {
if (_i34 >= _iterator32.length) break;
_ref31 = _iterator32[_i34++];
} else {
_i34 = _iterator32.next();
if (_i34.done) break;
_ref31 = _i34.value;
}
var file = _ref31;
file.status = Dropzone.ERROR;
this.emit("error", file, message, xhr);
this.emit("complete", file);
}
if (this.options.uploadMultiple) {
this.emit("errormultiple", files, message, xhr);
this.emit("completemultiple", files);
}
if (this.options.autoProcessQueue) {
return this.processQueue();
}
},
},
],
[
{
key: "uuidv4",
value: function uuidv4() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
/[xy]/g,
function (c) {
var r = (Math.random() * 16) | 0,
v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
}
);
},
},
]
);
return Dropzone;
})(Emitter);
Dropzone.initClass();
Dropzone.version = "5.5.1";
Dropzone.options = {};
Dropzone.optionsForElement = function (element) {
if (element.getAttribute("id")) {
return Dropzone.options[camelize(element.getAttribute("id"))];
} else {
return undefined;
}
};
Dropzone.instances = [];
Dropzone.forElement = function (element) {
if (typeof element === "string") {
element = document.querySelector(element);
}
if ((element != null ? element.dropzone : undefined) == null) {
throw new Error(
"No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."
);
}
return element.dropzone;
};
Dropzone.autoDiscover = true;
Dropzone.discover = function () {
var dropzones = void 0;
if (document.querySelectorAll) {
dropzones = document.querySelectorAll(".dropzone");
} else {
dropzones = [];
var checkElements = function checkElements(elements) {
return (function () {
var result = [];
for (
var _iterator33 = elements,
_isArray33 = true,
_i35 = 0,
_iterator33 = _isArray33
? _iterator33
: _iterator33[Symbol.iterator]();
;
) {
var _ref32;
if (_isArray33) {
if (_i35 >= _iterator33.length) break;
_ref32 = _iterator33[_i35++];
} else {
_i35 = _iterator33.next();
if (_i35.done) break;
_ref32 = _i35.value;
}
var el = _ref32;
if (/(^| )dropzone($| )/.test(el.className)) {
result.push(dropzones.push(el));
} else {
result.push(undefined);
}
}
return result;
})();
};
checkElements(document.getElementsByTagName("div"));
checkElements(document.getElementsByTagName("form"));
}
return (function () {
var result = [];
for (
var _iterator34 = dropzones,
_isArray34 = true,
_i36 = 0,
_iterator34 = _isArray34
? _iterator34
: _iterator34[Symbol.iterator]();
;
) {
var _ref33;
if (_isArray34) {
if (_i36 >= _iterator34.length) break;
_ref33 = _iterator34[_i36++];
} else {
_i36 = _iterator34.next();
if (_i36.done) break;
_ref33 = _i36.value;
}
var dropzone = _ref33;
if (Dropzone.optionsForElement(dropzone) !== false) {
result.push(new Dropzone(dropzone));
} else {
result.push(undefined);
}
}
return result;
})();
};
Dropzone.blacklistedBrowsers = [
/opera.*(Macintosh|Windows Phone).*version\/12/i,
];
Dropzone.isBrowserSupported = function () {
var capableBrowser = true;
if (
window.File &&
window.FileReader &&
window.FileList &&
window.Blob &&
window.FormData &&
document.querySelector
) {
if (!("classList" in document.createElement("a"))) {
capableBrowser = false;
} else {
for (
var _iterator35 = Dropzone.blacklistedBrowsers,
_isArray35 = true,
_i37 = 0,
_iterator35 = _isArray35
? _iterator35
: _iterator35[Symbol.iterator]();
;
) {
var _ref34;
if (_isArray35) {
if (_i37 >= _iterator35.length) break;
_ref34 = _iterator35[_i37++];
} else {
_i37 = _iterator35.next();
if (_i37.done) break;
_ref34 = _i37.value;
}
var regex = _ref34;
if (regex.test(navigator.userAgent)) {
capableBrowser = false;
continue;
}
}
}
} else {
capableBrowser = false;
}
return capableBrowser;
};
Dropzone.dataURItoBlob = function (dataURI) {
var byteString = atob(dataURI.split(",")[1]);
var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (
var i = 0, end = byteString.length, asc = 0 <= end;
asc ? i <= end : i >= end;
asc ? i++ : i--
) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: mimeString });
};
var without = function without(list, rejectedItem) {
return list
.filter(function (item) {
return item !== rejectedItem;
})
.map(function (item) {
return item;
});
};
var camelize = function camelize(str) {
return str.replace(/[\-_](\w)/g, function (match) {
return match.charAt(1).toUpperCase();
});
};
Dropzone.createElement = function (string) {
var div = document.createElement("div");
div.innerHTML = string;
return div.childNodes[0];
};
Dropzone.elementInside = function (element, container) {
if (element === container) {
return true;
}
while ((element = element.parentNode)) {
if (element === container) {
return true;
}
}
return false;
};
Dropzone.getElement = function (el, name) {
var element = void 0;
if (typeof el === "string") {
element = document.querySelector(el);
} else if (el.nodeType != null) {
element = el;
}
if (element == null) {
throw new Error(
"Invalid `" +
name +
"` option provided. Please provide a CSS selector or a plain HTML element."
);
}
return element;
};
Dropzone.getElements = function (els, name) {
var el = void 0,
elements = void 0;
if (els instanceof Array) {
elements = [];
try {
for (
var _iterator36 = els,
_isArray36 = true,
_i38 = 0,
_iterator36 = _isArray36
? _iterator36
: _iterator36[Symbol.iterator]();
;
) {
if (_isArray36) {
if (_i38 >= _iterator36.length) break;
el = _iterator36[_i38++];
} else {
_i38 = _iterator36.next();
if (_i38.done) break;
el = _i38.value;
}
elements.push(this.getElement(el, name));
}
} catch (e) {
elements = null;
}
} else if (typeof els === "string") {
elements = [];
for (
var _iterator37 = document.querySelectorAll(els),
_isArray37 = true,
_i39 = 0,
_iterator37 = _isArray37
? _iterator37
: _iterator37[Symbol.iterator]();
;
) {
if (_isArray37) {
if (_i39 >= _iterator37.length) break;
el = _iterator37[_i39++];
} else {
_i39 = _iterator37.next();
if (_i39.done) break;
el = _i39.value;
}
elements.push(el);
}
} else if (els.nodeType != null) {
elements = [els];
}
if (elements == null || !elements.length) {
throw new Error(
"Invalid `" +
name +
"` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
);
}
return elements;
};
Dropzone.confirm = function (question, accepted, rejected) {
if (window.confirm(question)) {
return accepted();
} else if (rejected != null) {
return rejected();
}
};
Dropzone.isValidFile = function (file, acceptedFiles) {
if (!acceptedFiles) {
return true;
}
acceptedFiles = acceptedFiles.split(",");
var mimeType = file.type;
var baseMimeType = mimeType.replace(/\/.*$/, "");
for (
var _iterator38 = acceptedFiles,
_isArray38 = true,
_i40 = 0,
_iterator38 = _isArray38
? _iterator38
: _iterator38[Symbol.iterator]();
;
) {
var _ref35;
if (_isArray38) {
if (_i40 >= _iterator38.length) break;
_ref35 = _iterator38[_i40++];
} else {
_i40 = _iterator38.next();
if (_i40.done) break;
_ref35 = _i40.value;
}
var validType = _ref35;
validType = validType.trim();
if (validType.charAt(0) === ".") {
if (
file.name
.toLowerCase()
.indexOf(
validType.toLowerCase(),
file.name.length - validType.length
) !== -1
) {
return true;
}
} else if (/\/\*$/.test(validType)) {
if (baseMimeType === validType.replace(/\/.*$/, "")) {
return true;
}
} else {
if (mimeType === validType) {
return true;
}
}
}
return false;
};
if (typeof jQuery !== "undefined" && jQuery !== null) {
jQuery.fn.dropzone = function (options) {
return this.each(function () {
return new Dropzone(this, options);
});
};
}
if (typeof module !== "undefined" && module !== null) {
module.exports = Dropzone;
} else {
window.Dropzone = Dropzone;
}
Dropzone.ADDED = "added";
Dropzone.QUEUED = "queued";
Dropzone.ACCEPTED = Dropzone.QUEUED;
Dropzone.UPLOADING = "uploading";
Dropzone.PROCESSING = Dropzone.UPLOADING;
Dropzone.CANCELED = "canceled";
Dropzone.ERROR = "error";
Dropzone.SUCCESS = "success";
var detectVerticalSquash = function detectVerticalSquash(img) {
var iw = img.naturalWidth;
var ih = img.naturalHeight;
var canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = ih;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var _ctx$getImageData = ctx.getImageData(1, 0, 1, ih),
data = _ctx$getImageData.data;
var sy = 0;
var ey = ih;
var py = ih;
while (py > sy) {
var alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
var ratio = py / ih;
if (ratio === 0) {
return 1;
} else {
return ratio;
}
};
var drawImageIOSFix = function drawImageIOSFix(
ctx,
img,
sx,
sy,
sw,
sh,
dx,
dy,
dw,
dh
) {
var vertSquashRatio = detectVerticalSquash(img);
return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
};
var ExifRestore = (function () {
function ExifRestore() {
_classCallCheck(this, ExifRestore);
}
_createClass(ExifRestore, null, [
{
key: "initClass",
value: function initClass() {
this.KEY_STR =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
},
},
{
key: "encode64",
value: function encode64(input) {
var output = "";
var chr1 = undefined;
var chr2 = undefined;
var chr3 = "";
var enc1 = undefined;
var enc2 = undefined;
var enc3 = undefined;
var enc4 = "";
var i = 0;
while (true) {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output =
output +
this.KEY_STR.charAt(enc1) +
this.KEY_STR.charAt(enc2) +
this.KEY_STR.charAt(enc3) +
this.KEY_STR.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
if (!(i < input.length)) {
break;
}
}
return output;
},
},
{
key: "restore",
value: function restore(origFileBase64, resizedFileBase64) {
if (!origFileBase64.match("data:image/jpeg;base64,")) {
return resizedFileBase64;
}
var rawImage = this.decode64(
origFileBase64.replace("data:image/jpeg;base64,", "")
);
var segments = this.slice2Segments(rawImage);
var image = this.exifManipulation(resizedFileBase64, segments);
return "data:image/jpeg;base64," + this.encode64(image);
},
},
{
key: "exifManipulation",
value: function exifManipulation(resizedFileBase64, segments) {
var exifArray = this.getExifArray(segments);
var newImageArray = this.insertExif(
resizedFileBase64,
exifArray
);
var aBuffer = new Uint8Array(newImageArray);
return aBuffer;
},
},
{
key: "getExifArray",
value: function getExifArray(segments) {
var seg = undefined;
var x = 0;
while (x < segments.length) {
seg = segments[x];
if ((seg[0] === 255) & (seg[1] === 225)) {
return seg;
}
x++;
}
return [];
},
},
{
key: "insertExif",
value: function insertExif(resizedFileBase64, exifArray) {
var imageData = resizedFileBase64.replace(
"data:image/jpeg;base64,",
""
);
var buf = this.decode64(imageData);
var separatePoint = buf.indexOf(255, 3);
var mae = buf.slice(0, separatePoint);
var ato = buf.slice(separatePoint);
var array = mae;
array = array.concat(exifArray);
array = array.concat(ato);
return array;
},
},
{
key: "slice2Segments",
value: function slice2Segments(rawImageArray) {
var head = 0;
var segments = [];
while (true) {
var length;
if (
(rawImageArray[head] === 255) &
(rawImageArray[head + 1] === 218)
) {
break;
}
if (
(rawImageArray[head] === 255) &
(rawImageArray[head + 1] === 216)
) {
head += 2;
} else {
length =
rawImageArray[head + 2] * 256 +
rawImageArray[head + 3];
var endPoint = head + length + 2;
var seg = rawImageArray.slice(head, endPoint);
segments.push(seg);
head = endPoint;
}
if (head > rawImageArray.length) {
break;
}
}
return segments;
},
},
{
key: "decode64",
value: function decode64(input) {
var output = "";
var chr1 = undefined;
var chr2 = undefined;
var chr3 = "";
var enc1 = undefined;
var enc2 = undefined;
var enc3 = undefined;
var enc4 = "";
var i = 0;
var buf = [];
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
console.warn(
"There were invalid base64 characters in the input text.\nValid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\nExpect errors in decoding."
);
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (true) {
enc1 = this.KEY_STR.indexOf(input.charAt(i++));
enc2 = this.KEY_STR.indexOf(input.charAt(i++));
enc3 = this.KEY_STR.indexOf(input.charAt(i++));
enc4 = this.KEY_STR.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
buf.push(chr1);
if (enc3 !== 64) {
buf.push(chr2);
}
if (enc4 !== 64) {
buf.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
if (!(i < input.length)) {
break;
}
}
return buf;
},
},
]);
return ExifRestore;
})();
ExifRestore.initClass();
var contentLoaded = function contentLoaded(win, fn) {
var done = false;
var top = true;
var doc = win.document;
var root = doc.documentElement;
var add = doc.addEventListener ? "addEventListener" : "attachEvent";
var rem = doc.addEventListener ? "removeEventListener" : "detachEvent";
var pre = doc.addEventListener ? "" : "on";
var init = function init(e) {
if (e.type === "readystatechange" && doc.readyState !== "complete") {
return;
}
(e.type === "load" ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) {
return fn.call(win, e.type || e);
}
};
var poll = function poll() {
try {
root.doScroll("left");
} catch (e) {
setTimeout(poll, 50);
return;
}
return init("poll");
};
if (doc.readyState !== "complete") {
if (doc.createEventObject && root.doScroll) {
try {
top = !win.frameElement;
} catch (error) {}
if (top) {
poll();
}
}
doc[add](pre + "DOMContentLoaded", init, false);
doc[add](pre + "readystatechange", init, false);
return win[add](pre + "load", init, false);
}
};
Dropzone._autoDiscoverFunction = function () {
if (Dropzone.autoDiscover) {
return Dropzone.discover();
}
};
contentLoaded(window, Dropzone._autoDiscoverFunction);
function __guard__(value, transform) {
return typeof value !== "undefined" && value !== null
? transform(value)
: undefined;
}
function __guardMethod__(obj, methodName, transform) {
if (
typeof obj !== "undefined" &&
obj !== null &&
typeof obj[methodName] === "function"
) {
return transform(obj, methodName);
} else {
return undefined;
}
}
(function (window, document) {
var modalClass = ".sweet-alert",
overlayClass = ".sweet-overlay",
alertTypes = ["error", "warning", "info", "success"],
defaultParams = {
title: "",
text: "",
type: null,
allowOutsideClick: false,
showCancelButton: false,
showConfirmButton: true,
closeOnConfirm: true,
closeOnCancel: true,
confirmButtonText: "OK",
confirmButtonClass: "btn-primary",
cancelButtonText: "Cancel",
cancelButtonClass: "btn-default",
containerClass: "",
titleClass: "",
textClass: "",
imageUrl: null,
imageSize: null,
timer: null,
};
var getModal = function () {
return document.querySelector(modalClass);
},
getOverlay = function () {
return document.querySelector(overlayClass);
},
hasClass = function (elem, className) {
return new RegExp(" " + className + " ").test(
" " + elem.className + " "
);
},
addClass = function (elem, className) {
if (className && !hasClass(elem, className)) {
elem.className += " " + className;
}
},
removeClass = function (elem, className) {
var newClass = " " + elem.className.replace(/[\t\r\n]/g, " ") + " ";
if (hasClass(elem, className)) {
while (newClass.indexOf(" " + className + " ") >= 0) {
newClass = newClass.replace(" " + className + " ", " ");
}
elem.className = newClass.replace(/^\s+|\s+$/g, "");
}
},
escapeHtml = function (str) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(str));
return div.innerHTML;
},
_show = function (elem) {
elem.style.opacity = "";
elem.style.display = "block";
},
show = function (elems) {
if (elems && !elems.length) {
return _show(elems);
}
for (var i = 0; i < elems.length; ++i) {
_show(elems[i]);
}
},
_hide = function (elem) {
elem.style.opacity = "";
elem.style.display = "none";
},
hide = function (elems) {
if (elems && !elems.length) {
return _hide(elems);
}
for (var i = 0; i < elems.length; ++i) {
_hide(elems[i]);
}
},
isDescendant = function (parent, child) {
var node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
},
getTopMargin = function (elem) {
elem.style.left = "-9999px";
elem.style.display = "block";
var height = elem.clientHeight;
var padding = parseInt(
getComputedStyle(elem).getPropertyValue("padding"),
10
);
elem.style.left = "";
elem.style.display = "none";
return "-" + parseInt(height / 2 + padding) + "px";
},
fadeIn = function (elem, interval) {
if (+elem.style.opacity < 1) {
interval = interval || 16;
elem.style.opacity = 0;
elem.style.display = "block";
var last = +new Date();
var tick = function () {
elem.style.opacity =
+elem.style.opacity + (new Date() - last) / 100;
last = +new Date();
if (+elem.style.opacity < 1) {
setTimeout(tick, interval);
}
};
tick();
}
},
fadeOut = function (elem, interval) {
interval = interval || 16;
elem.style.opacity = 1;
var last = +new Date();
var tick = function () {
elem.style.opacity =
+elem.style.opacity - (new Date() - last) / 100;
last = +new Date();
if (+elem.style.opacity > 0) {
setTimeout(tick, interval);
} else {
elem.style.display = "none";
}
};
tick();
},
fireClick = function (node) {
if (MouseEvent) {
var mevt = new MouseEvent("click", {
view: window,
bubbles: false,
cancelable: true,
});
node.dispatchEvent(mevt);
} else if (document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", false, false);
node.dispatchEvent(evt);
} else if (document.createEventObject) {
node.fireEvent("onclick");
} else if (typeof node.onclick === "function") {
node.onclick();
}
},
stopEventPropagation = function (e) {
if (typeof e.stopPropagation === "function") {
e.stopPropagation();
e.preventDefault();
} else if (
window.event &&
window.event.hasOwnProperty("cancelBubble")
) {
window.event.cancelBubble = true;
}
};
var previousActiveElement,
previousDocumentClick,
previousWindowKeyDown,
lastFocusedButton;
window.sweetAlertInitialize = function () {
var sweetHTML =
'<div class="sweet-overlay"></div><div class="sweet-alert"><div class="icon error"><span class="x-mark"><span class="line left"></span><span class="line right"></span></span></div><div class="icon warning"> <span class="body"></span> <span class="dot"></span> </div> <div class="icon info"></div> <div class="icon success"> <span class="line tip"></span> <span class="line long"></span> <div class="placeholder"></div> <div class="fix"></div> </div> <div class="icon custom"></div> <h2>Title</h2><p class="lead text-muted">Text</p><p><button class="cancel btn" tabIndex="2">Cancel</button> <button class="confirm btn" tabIndex="1">OK</button></p></div>',
sweetWrap = document.createElement("div");
sweetWrap.innerHTML = sweetHTML;
document.body.appendChild(sweetWrap);
};
window.sweetAlert = window.swal = function () {
if (arguments[0] === undefined) {
window.console.error("sweetAlert expects at least 1 attribute!");
return false;
}
var params = extend({}, defaultParams);
switch (typeof arguments[0]) {
case "string":
params.title = arguments[0];
params.text = arguments[1] || "";
params.type = arguments[2] || "";
break;
case "object":
if (arguments[0].title === undefined) {
window.console.error('Missing "title" argument!');
return false;
}
params.title = arguments[0].title;
params.text = arguments[0].text || defaultParams.text;
params.type = arguments[0].type || defaultParams.type;
params.allowOutsideClick =
arguments[0].allowOutsideClick ||
defaultParams.allowOutsideClick;
params.showCancelButton =
arguments[0].showCancelButton !== undefined
? arguments[0].showCancelButton
: defaultParams.showCancelButton;
params.showConfirmButton =
arguments[0].showConfirmButton !== undefined
? arguments[0].showConfirmButton
: defaultParams.showConfirmButton;
params.closeOnConfirm =
arguments[0].closeOnConfirm !== undefined
? arguments[0].closeOnConfirm
: defaultParams.closeOnConfirm;
params.closeOnCancel =
arguments[0].closeOnCancel !== undefined
? arguments[0].closeOnCancel
: defaultParams.closeOnCancel;
params.timer = arguments[0].timer || defaultParams.timer;
params.confirmButtonText = defaultParams.showCancelButton
? "Confirm"
: defaultParams.confirmButtonText;
params.confirmButtonText =
arguments[0].confirmButtonText ||
defaultParams.confirmButtonText;
params.confirmButtonClass =
arguments[0].confirmButtonClass ||
(arguments[0].type ? "btn-" + arguments[0].type : null) ||
defaultParams.confirmButtonClass;
params.cancelButtonText =
arguments[0].cancelButtonText ||
defaultParams.cancelButtonText;
params.cancelButtonClass =
arguments[0].cancelButtonClass ||
defaultParams.cancelButtonClass;
params.containerClass =
arguments[0].containerClass || defaultParams.containerClass;
params.titleClass =
arguments[0].titleClass || defaultParams.titleClass;
params.textClass =
arguments[0].textClass || defaultParams.textClass;
params.imageUrl =
arguments[0].imageUrl || defaultParams.imageUrl;
params.imageSize =
arguments[0].imageSize || defaultParams.imageSize;
params.doneFunction = arguments[1] || null;
break;
default:
window.console.error(
'Unexpected type of argument! Expected "string" or "object", got ' +
typeof arguments[0]
);
return false;
}
setParameters(params);
fixVerticalPosition();
openModal();
var modal = getModal();
var onButtonEvent = function (e) {
var target = e.target || e.srcElement,
targetedConfirm = target.className.indexOf("confirm") > -1,
modalIsVisible = hasClass(modal, "visible"),
doneFunctionExists =
params.doneFunction &&
modal.getAttribute("data-has-done-function") === "true";
switch (e.type) {
case "click":
if (
targetedConfirm &&
doneFunctionExists &&
modalIsVisible
) {
params.doneFunction(true);
if (params.closeOnConfirm) {
closeModal();
}
} else if (doneFunctionExists && modalIsVisible) {
var functionAsStr = String(params.doneFunction).replace(
/\s/g,
""
);
var functionHandlesCancel =
functionAsStr.substring(0, 9) === "function(" &&
functionAsStr.substring(9, 10) !== ")";
if (functionHandlesCancel) {
params.doneFunction(false);
}
if (params.closeOnCancel) {
closeModal();
}
} else {
closeModal();
}
break;
}
};
var $buttons = modal.querySelectorAll("button");
for (var i = 0; i < $buttons.length; i++) {
$buttons[i].onclick = onButtonEvent;
}
previousDocumentClick = document.onclick;
document.onclick = function (e) {
var target = e.target || e.srcElement;
var clickedOnModal = modal === target,
clickedOnModalChild = isDescendant(modal, e.target),
modalIsVisible = hasClass(modal, "visible"),
outsideClickIsAllowed =
modal.getAttribute("data-allow-ouside-click") === "true";
if (
!clickedOnModal &&
!clickedOnModalChild &&
modalIsVisible &&
outsideClickIsAllowed
) {
closeModal();
}
};
var $okButton = modal.querySelector("button.confirm"),
$cancelButton = modal.querySelector("button.cancel"),
$modalButtons = modal.querySelectorAll("button:not([type=hidden])");
function handleKeyDown(e) {
var keyCode = e.keyCode || e.which;
if ([9, 13, 32, 27].indexOf(keyCode) === -1) {
return;
}
var $targetElement = e.target || e.srcElement;
var btnIndex = -1;
for (var i = 0; i < $modalButtons.length; i++) {
if ($targetElement === $modalButtons[i]) {
btnIndex = i;
break;
}
}
if (keyCode === 9) {
if (btnIndex === -1) {
$targetElement = $okButton;
} else {
if (btnIndex === $modalButtons.length - 1) {
$targetElement = $modalButtons[0];
} else {
$targetElement = $modalButtons[btnIndex + 1];
}
}
stopEventPropagation(e);
$targetElement.focus();
} else {
if (keyCode === 13 || keyCode === 32) {
if (btnIndex === -1) {
$targetElement = $okButton;
} else {
$targetElement = undefined;
}
} else if (
keyCode === 27 &&
!(
$cancelButton.hidden ||
$cancelButton.style.display === "none"
)
) {
$targetElement = $cancelButton;
} else {
$targetElement = undefined;
}
if ($targetElement !== undefined) {
fireClick($targetElement, e);
}
}
}
previousWindowKeyDown = window.onkeydown;
window.onkeydown = handleKeyDown;
function handleOnBlur(e) {
var $targetElement = e.target || e.srcElement,
$focusElement = e.relatedTarget,
modalIsVisible = hasClass(modal, "visible"),
bootstrapModalIsVisible =
document.querySelector(".control-popup.modal") || false;
if (bootstrapModalIsVisible) {
return;
}
if (modalIsVisible) {
var btnIndex = -1;
if ($focusElement !== null) {
for (var i = 0; i < $modalButtons.length; i++) {
if ($focusElement === $modalButtons[i]) {
btnIndex = i;
break;
}
}
if (btnIndex === -1) {
$targetElement.focus();
}
} else {
lastFocusedButton = $targetElement;
}
}
}
$okButton.onblur = handleOnBlur;
$cancelButton.onblur = handleOnBlur;
window.onfocus = function () {
window.setTimeout(function () {
if (lastFocusedButton !== undefined) {
lastFocusedButton.focus();
lastFocusedButton = undefined;
}
}, 0);
};
};
window.swal.setDefaults = function (userParams) {
if (!userParams) {
throw new Error("userParams is required");
}
if (typeof userParams !== "object") {
throw new Error("userParams has to be a object");
}
extend(defaultParams, userParams);
};
window.swal.close = function () {
closeModal();
};
function setParameters(params) {
var modal = getModal();
var $title = modal.querySelector("h2"),
$text = modal.querySelector("p"),
$cancelBtn = modal.querySelector("button.cancel"),
$confirmBtn = modal.querySelector("button.confirm");
$title.innerHTML = escapeHtml(params.title).split("\n").join("<br>");
$text.innerHTML = escapeHtml(params.text || "")
.split("\n")
.join("<br>");
if (params.text) {
show($text);
}
hide(modal.querySelectorAll(".icon"));
if (params.type) {
var validType = false;
for (var i = 0; i < alertTypes.length; i++) {
if (params.type === alertTypes[i]) {
validType = true;
break;
}
}
if (!validType) {
window.console.error("Unknown alert type: " + params.type);
return false;
}
var $icon = modal.querySelector(".icon." + params.type);
show($icon);
switch (params.type) {
case "success":
addClass($icon, "animate");
addClass($icon.querySelector(".tip"), "animateSuccessTip");
addClass(
$icon.querySelector(".long"),
"animateSuccessLong"
);
break;
case "error":
addClass($icon, "animateErrorIcon");
addClass($icon.querySelector(".x-mark"), "animateXMark");
break;
case "warning":
addClass($icon, "pulseWarning");
addClass($icon.querySelector(".body"), "pulseWarningIns");
addClass($icon.querySelector(".dot"), "pulseWarningIns");
break;
}
}
if (params.imageUrl) {
var $customIcon = modal.querySelector(".icon.custom");
$customIcon.style.backgroundImage = "url(" + params.imageUrl + ")";
show($customIcon);
var _imgWidth = 80,
_imgHeight = 80;
if (params.imageSize) {
var imgWidth = params.imageSize.split("x")[0];
var imgHeight = params.imageSize.split("x")[1];
if (!imgWidth || !imgHeight) {
window.console.error(
"Parameter imageSize expects value with format WIDTHxHEIGHT, got " +
params.imageSize
);
} else {
_imgWidth = imgWidth;
_imgHeight = imgHeight;
$customIcon.css({
width: imgWidth + "px",
height: imgHeight + "px",
});
}
}
$customIcon.setAttribute(
"style",
$customIcon.getAttribute("style") +
"width:" +
_imgWidth +
"px; height:" +
_imgHeight +
"px"
);
}
modal.setAttribute("data-has-cancel-button", params.showCancelButton);
if (params.showCancelButton) {
$cancelBtn.style.display = "inline-block";
} else {
hide($cancelBtn);
}
modal.setAttribute("data-has-confirm-button", params.showConfirmButton);
if (params.showConfirmButton) {
$confirmBtn.style.display = "inline-block";
} else {
hide($confirmBtn);
}
if (params.cancelButtonText) {
$cancelBtn.innerHTML = escapeHtml(params.cancelButtonText);
}
if (params.confirmButtonText) {
$confirmBtn.innerHTML = escapeHtml(params.confirmButtonText);
}
$confirmBtn.className = "confirm btn";
addClass(modal, params.containerClass);
addClass($confirmBtn, params.confirmButtonClass);
addClass($cancelBtn, params.cancelButtonClass);
addClass($title, params.titleClass);
addClass($text, params.textClass);
modal.setAttribute("data-allow-ouside-click", params.allowOutsideClick);
var hasDoneFunction = params.doneFunction ? true : false;
modal.setAttribute("data-has-done-function", hasDoneFunction);
modal.setAttribute("data-timer", params.timer);
}
function colorLuminance(hex, lum) {
hex = String(hex).replace(/[^0-9a-f]/gi, "");
if (hex.length < 6) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
lum = lum || 0;
var rgb = "#",
c,
i;
for (i = 0; i < 3; i++) {
c = parseInt(hex.substr(i * 2, 2), 16);
c = Math.round(Math.min(Math.max(0, c + c * lum), 255)).toString(
16
);
rgb += ("00" + c).substr(c.length);
}
return rgb;
}
function extend(a, b) {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
return a;
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? parseInt(result[1], 16) +
", " +
parseInt(result[2], 16) +
", " +
parseInt(result[3], 16)
: null;
}
function setFocusStyle($button, bgColor) {
var rgbColor = hexToRgb(bgColor);
$button.style.boxShadow =
"0 0 2px rgba(" +
rgbColor +
", 0.8), inset 0 0 0 1px rgba(0, 0, 0, 0.05)";
}
function openModal() {
var modal = getModal();
fadeIn(getOverlay(), 10);
show(modal);
addClass(modal, "showSweetAlert");
removeClass(modal, "hideSweetAlert");
previousActiveElement = document.activeElement;
var $okButton = modal.querySelector("button.confirm");
$okButton.focus();
setTimeout(function () {
addClass(modal, "visible");
}, 500);
var timer = modal.getAttribute("data-timer");
if (timer !== "null" && timer !== "") {
setTimeout(function () {
closeModal();
}, timer);
}
}
function closeModal() {
var modal = getModal();
fadeOut(getOverlay(), 5);
fadeOut(modal, 5);
removeClass(modal, "showSweetAlert");
addClass(modal, "hideSweetAlert");
removeClass(modal, "visible");
var $successIcon = modal.querySelector(".icon.success");
removeClass($successIcon, "animate");
removeClass($successIcon.querySelector(".tip"), "animateSuccessTip");
removeClass($successIcon.querySelector(".long"), "animateSuccessLong");
var $errorIcon = modal.querySelector(".icon.error");
removeClass($errorIcon, "animateErrorIcon");
removeClass($errorIcon.querySelector(".x-mark"), "animateXMark");
var $warningIcon = modal.querySelector(".icon.warning");
removeClass($warningIcon, "pulseWarning");
removeClass($warningIcon.querySelector(".body"), "pulseWarningIns");
removeClass($warningIcon.querySelector(".dot"), "pulseWarningIns");
window.onkeydown = previousWindowKeyDown;
document.onclick = previousDocumentClick;
if (previousActiveElement) {
previousActiveElement.focus();
}
lastFocusedButton = undefined;
}
function fixVerticalPosition() {
var modal = getModal();
modal.style.marginTop = getTopMargin(getModal());
}
(function () {
if (
document.readyState === "complete" ||
(document.readyState === "interactive" && document.body)
) {
sweetAlertInitialize();
} else {
if (document.addEventListener) {
document.addEventListener(
"DOMContentLoaded",
function handler() {
document.removeEventListener(
"DOMContentLoaded",
handler,
false
);
sweetAlertInitialize();
},
false
);
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function handler() {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", handler);
sweetAlertInitialize();
}
});
}
}
})();
})(window, document);
(function ($) {
$.Jcrop = function (obj, opt) {
var options = $.extend({}, $.Jcrop.defaults),
docOffset,
_ua = navigator.userAgent.toLowerCase(),
is_msie = /msie/.test(_ua),
ie6mode = /msie [1-6]\./.test(_ua);
function px(n) {
return Math.round(n) + "px";
}
function cssClass(cl) {
return options.baseClass + "-" + cl;
}
function supportsColorFade() {
return $.fx.step.hasOwnProperty("backgroundColor");
}
function getPos(obj) {
var pos = $(obj).offset();
return [pos.left, pos.top];
}
function mouseAbs(e) {
return [e.pageX - docOffset[0], e.pageY - docOffset[1]];
}
function setOptions(opt) {
if (typeof opt !== "object") opt = {};
options = $.extend(options, opt);
$.each(
["onChange", "onSelect", "onRelease", "onDblClick"],
function (i, e) {
if (typeof options[e] !== "function")
options[e] = function () {};
}
);
}
function startDragMode(mode, pos, touch) {
docOffset = getPos($img);
Tracker.setCursor(mode === "move" ? mode : mode + "-resize");
if (mode === "move") {
return Tracker.activateHandlers(
createMover(pos),
doneSelect,
touch
);
}
var fc = Coords.getFixed();
var opp = oppLockCorner(mode);
var opc = Coords.getCorner(oppLockCorner(opp));
Coords.setPressed(Coords.getCorner(opp));
Coords.setCurrent(opc);
Tracker.activateHandlers(
dragmodeHandler(mode, fc),
doneSelect,
touch
);
}
function dragmodeHandler(mode, f) {
return function (pos) {
if (!options.aspectRatio) {
switch (mode) {
case "e":
pos[1] = f.y2;
break;
case "w":
pos[1] = f.y2;
break;
case "n":
pos[0] = f.x2;
break;
case "s":
pos[0] = f.x2;
break;
}
} else {
switch (mode) {
case "e":
pos[1] = f.y + 1;
break;
case "w":
pos[1] = f.y + 1;
break;
case "n":
pos[0] = f.x + 1;
break;
case "s":
pos[0] = f.x + 1;
break;
}
}
Coords.setCurrent(pos);
Selection.update();
};
}
function createMover(pos) {
var lloc = pos;
KeyManager.watchKeys();
return function (pos) {
Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
lloc = pos;
Selection.update();
};
}
function oppLockCorner(ord) {
switch (ord) {
case "n":
return "sw";
case "s":
return "nw";
case "e":
return "nw";
case "w":
return "ne";
case "ne":
return "sw";
case "nw":
return "se";
case "se":
return "nw";
case "sw":
return "ne";
}
}
function createDragger(ord) {
return function (e) {
if (options.disabled) {
return false;
}
if (ord === "move" && !options.allowMove) {
return false;
}
docOffset = getPos($img);
btndown = true;
startDragMode(ord, mouseAbs(e));
e.stopPropagation();
e.preventDefault();
return false;
};
}
function presize($obj, w, h) {
var nw = $obj.width(),
nh = $obj.height();
if (nw > w && w > 0) {
nw = w;
nh = (w / $obj.width()) * $obj.height();
}
if (nh > h && h > 0) {
nh = h;
nw = (h / $obj.height()) * $obj.width();
}
xscale = $obj.width() / nw;
yscale = $obj.height() / nh;
$obj.width(nw).height(nh);
}
function unscale(c) {
return {
x: c.x * xscale,
y: c.y * yscale,
x2: c.x2 * xscale,
y2: c.y2 * yscale,
w: c.w * xscale,
h: c.h * yscale,
};
}
function doneSelect(pos) {
var c = Coords.getFixed();
if (c.w > options.minSelect[0] && c.h > options.minSelect[1]) {
Selection.enableHandles();
Selection.done();
} else {
Selection.release();
}
Tracker.setCursor(options.allowSelect ? "crosshair" : "default");
}
function newSelection(e) {
if (options.disabled) {
return false;
}
if (!options.allowSelect) {
return false;
}
btndown = true;
docOffset = getPos($img);
Selection.disableHandles();
Tracker.setCursor("crosshair");
var pos = mouseAbs(e);
Coords.setPressed(pos);
Selection.update();
Tracker.activateHandlers(
selectDrag,
doneSelect,
e.type.substring(0, 5) === "touch"
);
KeyManager.watchKeys();
e.stopPropagation();
e.preventDefault();
return false;
}
function selectDrag(pos) {
Coords.setCurrent(pos);
Selection.update();
}
function newTracker() {
var trk = $("<div></div>").addClass(cssClass("tracker"));
if (is_msie) {
trk.css({ opacity: 0, backgroundColor: "white" });
}
return trk;
}
if (typeof obj !== "object") {
obj = $(obj)[0];
}
if (typeof opt !== "object") {
opt = {};
}
setOptions(opt);
var img_css = {
border: "none",
visibility: "visible",
margin: 0,
padding: 0,
position: "absolute",
top: 0,
left: 0,
};
var $origimg = $(obj),
img_mode = true;
if (obj.tagName == "IMG") {
if ($origimg[0].width != 0 && $origimg[0].height != 0) {
$origimg.width($origimg[0].width);
$origimg.height($origimg[0].height);
} else {
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
}
var $img = $origimg.clone().removeAttr("id").css(img_css).show();
$img.width($origimg.width());
$img.height($origimg.height());
$origimg.after($img).hide();
} else {
$img = $origimg.css(img_css).show();
img_mode = false;
if (options.shade === null) {
options.shade = true;
}
}
presize($img, options.boxWidth, options.boxHeight);
var boundx = $img.width(),
boundy = $img.height(),
$div = $("<div />")
.width(boundx)
.height(boundy)
.addClass(cssClass("holder"))
.css({ position: "relative", backgroundColor: options.bgColor })
.insertAfter($origimg)
.append($img);
if (options.addClass) {
$div.addClass(options.addClass);
}
var $img2 = $("<div />"),
$img_holder = $("<div />")
.width("100%")
.height("100%")
.css({ zIndex: 310, position: "absolute", overflow: "hidden" }),
$hdl_holder = $("<div />")
.width("100%")
.height("100%")
.css("zIndex", 320),
$sel = $("<div />")
.css({ position: "absolute", zIndex: 600 })
.dblclick(function () {
var c = Coords.getFixed();
options.onDblClick.call(api, c);
})
.insertBefore($img)
.append($img_holder, $hdl_holder);
if (img_mode) {
($img2 = $("<img />")
.attr("src", $img.attr("src"))
.css(img_css)
.width(boundx)
.height(boundy)),
$img_holder.append($img2);
}
if (ie6mode) {
$sel.css({ overflowY: "hidden" });
}
var bound = options.boundary;
var $trk = newTracker()
.width(boundx + bound * 2)
.height(boundy + bound * 2)
.css({
position: "absolute",
top: px(-bound),
left: px(-bound),
zIndex: 290,
})
.mousedown(newSelection);
var bgcolor = options.bgColor,
bgopacity = options.bgOpacity,
xlimit,
ylimit,
xmin,
ymin,
xscale,
yscale,
enabled = true,
btndown,
animating,
shift_down;
docOffset = getPos($img);
var Touch = (function () {
function hasTouchSupport() {
var support = {},
events = ["touchstart", "touchmove", "touchend"],
el = document.createElement("div"),
i;
try {
for (i = 0; i < events.length; i++) {
var eventName = events[i];
eventName = "on" + eventName;
var isSupported = eventName in el;
if (!isSupported) {
el.setAttribute(eventName, "return;");
isSupported = typeof el[eventName] == "function";
}
support[events[i]] = isSupported;
}
return (
support.touchstart &&
support.touchend &&
support.touchmove
);
} catch (err) {
return false;
}
}
function detectSupport() {
if (
options.touchSupport === true ||
options.touchSupport === false
)
return options.touchSupport;
else return hasTouchSupport();
}
return {
createDragger: function (ord) {
return function (e) {
if (options.disabled) {
return false;
}
if (ord === "move" && !options.allowMove) {
return false;
}
docOffset = getPos($img);
btndown = true;
startDragMode(ord, mouseAbs(Touch.cfilter(e)), true);
e.stopPropagation();
e.preventDefault();
return false;
};
},
newSelection: function (e) {
return newSelection(Touch.cfilter(e));
},
cfilter: function (e) {
e.pageX = e.originalEvent.changedTouches[0].pageX;
e.pageY = e.originalEvent.changedTouches[0].pageY;
return e;
},
fixTouchSupport: function (e) {
if ($(e.currentTarget).hasClass("jcrop-tracker"))
e.stopPropagation();
},
isSupported: hasTouchSupport,
support: detectSupport(),
};
})();
var Coords = (function () {
var x1 = 0,
y1 = 0,
x2 = 0,
y2 = 0,
ox,
oy;
function setPressed(pos) {
pos = rebound(pos);
x2 = x1 = pos[0];
y2 = y1 = pos[1];
}
function setCurrent(pos) {
pos = rebound(pos);
ox = pos[0] - x2;
oy = pos[1] - y2;
x2 = pos[0];
y2 = pos[1];
}
function getOffset() {
return [ox, oy];
}
function moveOffset(offset) {
var ox = offset[0],
oy = offset[1];
if (0 > x1 + ox) {
ox -= ox + x1;
}
if (0 > y1 + oy) {
oy -= oy + y1;
}
if (boundy < y2 + oy) {
oy += boundy - (y2 + oy);
}
if (boundx < x2 + ox) {
ox += boundx - (x2 + ox);
}
x1 += ox;
x2 += ox;
y1 += oy;
y2 += oy;
}
function getCorner(ord) {
var c = getFixed();
switch (ord) {
case "ne":
return [c.x2, c.y];
case "nw":
return [c.x, c.y];
case "se":
return [c.x2, c.y2];
case "sw":
return [c.x, c.y2];
}
}
function getFixed() {
if (!options.aspectRatio) {
return getRect();
}
var aspect = options.aspectRatio,
min_x = options.minSize[0] / xscale,
max_x = options.maxSize[0] / xscale,
max_y = options.maxSize[1] / yscale,
rw = x2 - x1,
rh = y2 - y1,
rwa = Math.abs(rw),
rha = Math.abs(rh),
real_ratio = rwa / rha,
xx,
yy,
w,
h;
if (max_x === 0) {
max_x = boundx * 10;
}
if (max_y === 0) {
max_y = boundy * 10;
}
if (real_ratio < aspect) {
yy = y2;
w = rha * aspect;
xx = rw < 0 ? x1 - w : w + x1;
if (xx < 0) {
xx = 0;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
} else if (xx > boundx) {
xx = boundx;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
}
} else {
xx = x2;
h = rwa / aspect;
yy = rh < 0 ? y1 - h : y1 + h;
if (yy < 0) {
yy = 0;
w = Math.abs((yy - y1) * aspect);
xx = rw < 0 ? x1 - w : w + x1;
} else if (yy > boundy) {
yy = boundy;
w = Math.abs(yy - y1) * aspect;
xx = rw < 0 ? x1 - w : w + x1;
}
}
if (xx > x1) {
if (xx - x1 < min_x) {
xx = x1 + min_x;
} else if (xx - x1 > max_x) {
xx = x1 + max_x;
}
if (yy > y1) {
yy = y1 + (xx - x1) / aspect;
} else {
yy = y1 - (xx - x1) / aspect;
}
} else if (xx < x1) {
if (x1 - xx < min_x) {
xx = x1 - min_x;
} else if (x1 - xx > max_x) {
xx = x1 - max_x;
}
if (yy > y1) {
yy = y1 + (x1 - xx) / aspect;
} else {
yy = y1 - (x1 - xx) / aspect;
}
}
if (xx < 0) {
x1 -= xx;
xx = 0;
} else if (xx > boundx) {
x1 -= xx - boundx;
xx = boundx;
}
if (yy < 0) {
y1 -= yy;
yy = 0;
} else if (yy > boundy) {
y1 -= yy - boundy;
yy = boundy;
}
return makeObj(flipCoords(x1, y1, xx, yy));
}
function rebound(p) {
if (p[0] < 0) p[0] = 0;
if (p[1] < 0) p[1] = 0;
if (p[0] > boundx) p[0] = boundx;
if (p[1] > boundy) p[1] = boundy;
return [Math.round(p[0]), Math.round(p[1])];
}
function flipCoords(x1, y1, x2, y2) {
var xa = x1,
xb = x2,
ya = y1,
yb = y2;
if (x2 < x1) {
xa = x2;
xb = x1;
}
if (y2 < y1) {
ya = y2;
yb = y1;
}
return [xa, ya, xb, yb];
}
function getRect() {
var xsize = x2 - x1,
ysize = y2 - y1,
delta;
if (xlimit && Math.abs(xsize) > xlimit) {
x2 = xsize > 0 ? x1 + xlimit : x1 - xlimit;
}
if (ylimit && Math.abs(ysize) > ylimit) {
y2 = ysize > 0 ? y1 + ylimit : y1 - ylimit;
}
if (ymin / yscale && Math.abs(ysize) < ymin / yscale) {
y2 = ysize > 0 ? y1 + ymin / yscale : y1 - ymin / yscale;
}
if (xmin / xscale && Math.abs(xsize) < xmin / xscale) {
x2 = xsize > 0 ? x1 + xmin / xscale : x1 - xmin / xscale;
}
if (x1 < 0) {
x2 -= x1;
x1 -= x1;
}
if (y1 < 0) {
y2 -= y1;
y1 -= y1;
}
if (x2 < 0) {
x1 -= x2;
x2 -= x2;
}
if (y2 < 0) {
y1 -= y2;
y2 -= y2;
}
if (x2 > boundx) {
delta = x2 - boundx;
x1 -= delta;
x2 -= delta;
}
if (y2 > boundy) {
delta = y2 - boundy;
y1 -= delta;
y2 -= delta;
}
if (x1 > boundx) {
delta = x1 - boundy;
y2 -= delta;
y1 -= delta;
}
if (y1 > boundy) {
delta = y1 - boundy;
y2 -= delta;
y1 -= delta;
}
return makeObj(flipCoords(x1, y1, x2, y2));
}
function makeObj(a) {
return {
x: a[0],
y: a[1],
x2: a[2],
y2: a[3],
w: a[2] - a[0],
h: a[3] - a[1],
};
}
return {
flipCoords: flipCoords,
setPressed: setPressed,
setCurrent: setCurrent,
getOffset: getOffset,
moveOffset: moveOffset,
getCorner: getCorner,
getFixed: getFixed,
};
})();
var Shade = (function () {
var enabled = false,
holder = $("<div />").css({
position: "absolute",
zIndex: 240,
opacity: 0,
}),
shades = {
top: createShade(),
left: createShade().height(boundy),
right: createShade().height(boundy),
bottom: createShade(),
};
function resizeShades(w, h) {
shades.left.css({ height: px(h) });
shades.right.css({ height: px(h) });
}
function updateAuto() {
return updateShade(Coords.getFixed());
}
function updateShade(c) {
shades.top.css({
left: px(c.x),
width: px(c.w),
height: px(c.y),
});
shades.bottom.css({
top: px(c.y2),
left: px(c.x),
width: px(c.w),
height: px(boundy - c.y2),
});
shades.right.css({ left: px(c.x2), width: px(boundx - c.x2) });
shades.left.css({ width: px(c.x) });
}
function createShade() {
return $("<div />")
.css({
position: "absolute",
backgroundColor: options.shadeColor || options.bgColor,
})
.appendTo(holder);
}
function enableShade() {
if (!enabled) {
enabled = true;
holder.insertBefore($img);
updateAuto();
Selection.setBgOpacity(1, 0, 1);
$img2.hide();
setBgColor(options.shadeColor || options.bgColor, 1);
if (Selection.isAwake()) {
setOpacity(options.bgOpacity, 1);
} else setOpacity(1, 1);
}
}
function setBgColor(color, now) {
colorChangeMacro(getShades(), color, now);
}
function disableShade() {
if (enabled) {
holder.remove();
$img2.show();
enabled = false;
if (Selection.isAwake()) {
Selection.setBgOpacity(options.bgOpacity, 1, 1);
} else {
Selection.setBgOpacity(1, 1, 1);
Selection.disableHandles();
}
colorChangeMacro($div, 0, 1);
}
}
function setOpacity(opacity, now) {
if (enabled) {
if (options.bgFade && !now) {
holder.animate(
{ opacity: 1 - opacity },
{ queue: false, duration: options.fadeTime }
);
} else holder.css({ opacity: 1 - opacity });
}
}
function refreshAll() {
options.shade ? enableShade() : disableShade();
if (Selection.isAwake()) setOpacity(options.bgOpacity);
}
function getShades() {
return holder.children();
}
return {
update: updateAuto,
updateRaw: updateShade,
getShades: getShades,
setBgColor: setBgColor,
enable: enableShade,
disable: disableShade,
resize: resizeShades,
refresh: refreshAll,
opacity: setOpacity,
};
})();
var Selection = (function () {
var awake,
hdep = 370,
borders = {},
handle = {},
dragbar = {},
seehandles = false;
function insertBorder(type) {
var jq = $("<div />")
.css({
position: "absolute",
opacity: options.borderOpacity,
})
.addClass(cssClass(type));
$img_holder.append(jq);
return jq;
}
function dragDiv(ord, zi) {
var jq = $("<div />")
.mousedown(createDragger(ord))
.css({
cursor: ord + "-resize",
position: "absolute",
zIndex: zi,
})
.addClass("ord-" + ord);
if (Touch.support) {
jq.bind("touchstart.jcrop", Touch.createDragger(ord));
}
$hdl_holder.append(jq);
return jq;
}
function insertHandle(ord) {
var hs = options.handleSize,
div = dragDiv(ord, hdep++)
.css({ opacity: options.handleOpacity })
.addClass(cssClass("handle"));
if (hs) {
div.width(hs).height(hs);
}
return div;
}
function insertDragbar(ord) {
return dragDiv(ord, hdep++).addClass("jcrop-dragbar");
}
function createDragbars(li) {
var i;
for (i = 0; i < li.length; i++) {
dragbar[li[i]] = insertDragbar(li[i]);
}
}
function createBorders(li) {
var cl, i;
for (i = 0; i < li.length; i++) {
switch (li[i]) {
case "n":
cl = "hline";
break;
case "s":
cl = "hline bottom";
break;
case "e":
cl = "vline right";
break;
case "w":
cl = "vline";
break;
}
borders[li[i]] = insertBorder(cl);
}
}
function createHandles(li) {
var i;
for (i = 0; i < li.length; i++) {
handle[li[i]] = insertHandle(li[i]);
}
}
function moveto(x, y) {
if (!options.shade) {
$img2.css({ top: px(-y), left: px(-x) });
}
$sel.css({ top: px(y), left: px(x) });
}
function resize(w, h) {
$sel.width(Math.round(w)).height(Math.round(h));
}
function refresh() {
var c = Coords.getFixed();
Coords.setPressed([c.x, c.y]);
Coords.setCurrent([c.x2, c.y2]);
updateVisible();
}
function updateVisible(select) {
if (awake) {
return update(select);
}
}
function update(select) {
var c = Coords.getFixed();
resize(c.w, c.h);
moveto(c.x, c.y);
if (options.shade) Shade.updateRaw(c);
awake || show();
if (select) {
options.onSelect.call(api, unscale(c));
} else {
options.onChange.call(api, unscale(c));
}
}
function setBgOpacity(opacity, force, now) {
if (!awake && !force) return;
if (options.bgFade && !now) {
$img.animate(
{ opacity: opacity },
{ queue: false, duration: options.fadeTime }
);
} else {
$img.css("opacity", opacity);
}
}
function show() {
$sel.show();
if (options.shade) Shade.opacity(bgopacity);
else setBgOpacity(bgopacity, true);
awake = true;
}
function release() {
disableHandles();
$sel.hide();
if (options.shade) Shade.opacity(1);
else setBgOpacity(1);
awake = false;
options.onRelease.call(api);
}
function showHandles() {
if (seehandles) {
$hdl_holder.show();
}
}
function enableHandles() {
seehandles = true;
if (options.allowResize) {
$hdl_holder.show();
return true;
}
}
function disableHandles() {
seehandles = false;
$hdl_holder.hide();
}
function animMode(v) {
if (v) {
animating = true;
disableHandles();
} else {
animating = false;
enableHandles();
}
}
function done() {
animMode(false);
refresh();
}
if (options.dragEdges && $.isArray(options.createDragbars))
createDragbars(options.createDragbars);
if ($.isArray(options.createHandles))
createHandles(options.createHandles);
if (options.drawBorders && $.isArray(options.createBorders))
createBorders(options.createBorders);
$(document).bind("touchstart.jcrop-ios", Touch.fixTouchSupport);
var $track = newTracker()
.mousedown(createDragger("move"))
.css({ cursor: "move", position: "absolute", zIndex: 360 });
if (Touch.support) {
$track.bind("touchstart.jcrop", Touch.createDragger("move"));
}
$img_holder.append($track);
disableHandles();
return {
updateVisible: updateVisible,
update: update,
release: release,
refresh: refresh,
isAwake: function () {
return awake;
},
setCursor: function (cursor) {
$track.css("cursor", cursor);
},
enableHandles: enableHandles,
enableOnly: function () {
seehandles = true;
},
showHandles: showHandles,
disableHandles: disableHandles,
animMode: animMode,
setBgOpacity: setBgOpacity,
done: done,
};
})();
var Tracker = (function () {
var onMove = function () {},
onDone = function () {},
trackDoc = options.trackDocument;
function toFront(touch) {
$trk.css({ zIndex: 450 });
if (touch)
$(document)
.bind("touchmove.jcrop", trackTouchMove)
.bind("touchend.jcrop", trackTouchEnd);
else if (trackDoc)
$(document)
.bind("mousemove.jcrop", trackMove)
.bind("mouseup.jcrop", trackUp);
}
function toBack() {
$trk.css({ zIndex: 290 });
$(document).unbind(".jcrop");
}
function trackMove(e) {
onMove(mouseAbs(e));
return false;
}
function trackUp(e) {
e.preventDefault();
e.stopPropagation();
if (btndown) {
btndown = false;
onDone(mouseAbs(e));
if (Selection.isAwake()) {
options.onSelect.call(api, unscale(Coords.getFixed()));
}
toBack();
onMove = function () {};
onDone = function () {};
}
return false;
}
function activateHandlers(move, done, touch) {
btndown = true;
onMove = move;
onDone = done;
toFront(touch);
return false;
}
function trackTouchMove(e) {
onMove(mouseAbs(Touch.cfilter(e)));
return false;
}
function trackTouchEnd(e) {
return trackUp(Touch.cfilter(e));
}
function setCursor(t) {
$trk.css("cursor", t);
}
if (!trackDoc) {
$trk.mousemove(trackMove).mouseup(trackUp).mouseout(trackUp);
}
$img.before($trk);
return { activateHandlers: activateHandlers, setCursor: setCursor };
})();
var KeyManager = (function () {
var $keymgr = $('<input type="radio" />')
.css({ position: "fixed", left: "-120px", width: "12px" })
.addClass("jcrop-keymgr"),
$keywrap = $("<div />")
.css({ position: "absolute", overflow: "hidden" })
.append($keymgr);
function watchKeys() {
if (options.keySupport) {
$keymgr.show();
$keymgr.focus();
}
}
function onBlur(e) {
$keymgr.hide();
}
function doNudge(e, x, y) {
if (options.allowMove) {
Coords.moveOffset([x, y]);
Selection.updateVisible(true);
}
e.preventDefault();
e.stopPropagation();
}
function parseKey(e) {
if (e.ctrlKey || e.metaKey) {
return true;
}
shift_down = e.shiftKey ? true : false;
var nudge = shift_down ? 10 : 1;
switch (e.keyCode) {
case 37:
doNudge(e, -nudge, 0);
break;
case 39:
doNudge(e, nudge, 0);
break;
case 38:
doNudge(e, 0, -nudge);
break;
case 40:
doNudge(e, 0, nudge);
break;
case 27:
if (options.allowSelect) Selection.release();
break;
case 9:
return true;
}
return false;
}
if (options.keySupport) {
$keymgr.keydown(parseKey).blur(onBlur);
if (ie6mode || !options.fixedSupport) {
$keymgr.css({ position: "absolute", left: "-20px" });
$keywrap.append($keymgr).insertBefore($img);
} else {
$keymgr.insertBefore($img);
}
}
return { watchKeys: watchKeys };
})();
function setClass(cname) {
$div.removeClass().addClass(cssClass("holder")).addClass(cname);
}
function animateTo(a, callback) {
var x1 = a[0] / xscale,
y1 = a[1] / yscale,
x2 = a[2] / xscale,
y2 = a[3] / yscale;
if (animating) {
return;
}
var animto = Coords.flipCoords(x1, y1, x2, y2),
c = Coords.getFixed(),
initcr = [c.x, c.y, c.x2, c.y2],
animat = initcr,
interv = options.animationDelay,
ix1 = animto[0] - initcr[0],
iy1 = animto[1] - initcr[1],
ix2 = animto[2] - initcr[2],
iy2 = animto[3] - initcr[3],
pcent = 0,
velocity = options.swingSpeed;
x1 = animat[0];
y1 = animat[1];
x2 = animat[2];
y2 = animat[3];
Selection.animMode(true);
var anim_timer;
function queueAnimator() {
window.setTimeout(animator, interv);
}
var animator = (function () {
return function () {
pcent += (100 - pcent) / velocity;
animat[0] = Math.round(x1 + (pcent / 100) * ix1);
animat[1] = Math.round(y1 + (pcent / 100) * iy1);
animat[2] = Math.round(x2 + (pcent / 100) * ix2);
animat[3] = Math.round(y2 + (pcent / 100) * iy2);
if (pcent >= 99.8) {
pcent = 100;
}
if (pcent < 100) {
setSelectRaw(animat);
queueAnimator();
} else {
Selection.done();
Selection.animMode(false);
if (typeof callback === "function") {
callback.call(api);
}
}
};
})();
queueAnimator();
}
function setSelect(rect) {
setSelectRaw([
rect[0] / xscale,
rect[1] / yscale,
rect[2] / xscale,
rect[3] / yscale,
]);
options.onSelect.call(api, unscale(Coords.getFixed()));
Selection.enableHandles();
}
function setSelectRaw(l) {
Coords.setPressed([l[0], l[1]]);
Coords.setCurrent([l[2], l[3]]);
Selection.update();
}
function tellSelect() {
return unscale(Coords.getFixed());
}
function tellScaled() {
return Coords.getFixed();
}
function setOptionsNew(opt) {
setOptions(opt);
interfaceUpdate();
}
function disableCrop() {
options.disabled = true;
Selection.disableHandles();
Selection.setCursor("default");
Tracker.setCursor("default");
}
function enableCrop() {
options.disabled = false;
interfaceUpdate();
}
function cancelCrop() {
Selection.done();
Tracker.activateHandlers(null, null);
}
function destroy() {
$(document).unbind("touchstart.jcrop-ios", Touch.fixTouchSupport);
$div.remove();
$origimg.show();
$origimg.css("visibility", "visible");
$(obj).removeData("Jcrop");
}
function setImage(src, callback) {
Selection.release();
disableCrop();
var img = new Image();
img.onload = function () {
var iw = img.width;
var ih = img.height;
var bw = options.boxWidth;
var bh = options.boxHeight;
$img.width(iw).height(ih);
$img.attr("src", src);
$img2.attr("src", src);
presize($img, bw, bh);
boundx = $img.width();
boundy = $img.height();
$img2.width(boundx).height(boundy);
$trk.width(boundx + bound * 2).height(boundy + bound * 2);
$div.width(boundx).height(boundy);
Shade.resize(boundx, boundy);
enableCrop();
if (typeof callback === "function") {
callback.call(api);
}
};
img.src = src;
}
function colorChangeMacro($obj, color, now) {
var mycolor = color || options.bgColor;
if (
options.bgFade &&
supportsColorFade() &&
options.fadeTime &&
!now
) {
$obj.animate(
{ backgroundColor: mycolor },
{ queue: false, duration: options.fadeTime }
);
} else {
$obj.css("backgroundColor", mycolor);
}
}
function interfaceUpdate(alt) {
if (options.allowResize) {
if (alt) {
Selection.enableOnly();
} else {
Selection.enableHandles();
}
} else {
Selection.disableHandles();
}
Tracker.setCursor(options.allowSelect ? "crosshair" : "default");
Selection.setCursor(options.allowMove ? "move" : "default");
if (options.hasOwnProperty("trueSize")) {
xscale = options.trueSize[0] / boundx;
yscale = options.trueSize[1] / boundy;
}
if (options.hasOwnProperty("setSelect")) {
setSelect(options.setSelect);
Selection.done();
delete options.setSelect;
}
Shade.refresh();
if (options.bgColor != bgcolor) {
colorChangeMacro(
options.shade ? Shade.getShades() : $div,
options.shade
? options.shadeColor || options.bgColor
: options.bgColor
);
bgcolor = options.bgColor;
}
if (bgopacity != options.bgOpacity) {
bgopacity = options.bgOpacity;
if (options.shade) Shade.refresh();
else Selection.setBgOpacity(bgopacity);
}
xlimit = options.maxSize[0] || 0;
ylimit = options.maxSize[1] || 0;
xmin = options.minSize[0] || 0;
ymin = options.minSize[1] || 0;
if (options.hasOwnProperty("outerImage")) {
$img.attr("src", options.outerImage);
delete options.outerImage;
}
Selection.refresh();
}
if (Touch.support) $trk.bind("touchstart.jcrop", Touch.newSelection);
$hdl_holder.hide();
interfaceUpdate(true);
var api = {
setImage: setImage,
animateTo: animateTo,
setSelect: setSelect,
setOptions: setOptionsNew,
tellSelect: tellSelect,
tellScaled: tellScaled,
setClass: setClass,
disable: disableCrop,
enable: enableCrop,
cancel: cancelCrop,
release: Selection.release,
destroy: destroy,
focus: KeyManager.watchKeys,
getBounds: function () {
return [boundx * xscale, boundy * yscale];
},
getWidgetSize: function () {
return [boundx, boundy];
},
getScaleFactor: function () {
return [xscale, yscale];
},
getOptions: function () {
return options;
},
ui: { holder: $div, selection: $sel },
};
if (is_msie)
$div.bind("selectstart", function () {
return false;
});
$origimg.data("Jcrop", api);
return api;
};
$.fn.Jcrop = function (options, callback) {
var api;
this.each(function () {
if ($(this).data("Jcrop")) {
if (options === "api") return $(this).data("Jcrop");
else $(this).data("Jcrop").setOptions(options);
} else {
if (this.tagName == "IMG")
$.Jcrop.Loader(this, function () {
$(this).css({ display: "block", visibility: "hidden" });
api = $.Jcrop(this, options);
if ($.isFunction(callback)) callback.call(api);
});
else {
$(this).css({ display: "block", visibility: "hidden" });
api = $.Jcrop(this, options);
if ($.isFunction(callback)) callback.call(api);
}
}
});
return this;
};
$.Jcrop.Loader = function (imgobj, success, error) {
var $img = $(imgobj),
img = $img[0];
function completeCheck() {
if (img.complete) {
$img.unbind(".jcloader");
if ($.isFunction(success)) success.call(img);
} else window.setTimeout(completeCheck, 50);
}
$img.bind("load.jcloader", completeCheck).bind(
"error.jcloader",
function (e) {
$img.unbind(".jcloader");
if ($.isFunction(error)) error.call(img);
}
);
if (img.complete && $.isFunction(success)) {
$img.unbind(".jcloader");
success.call(img);
}
};
$.Jcrop.defaults = {
allowSelect: true,
allowMove: true,
allowResize: true,
trackDocument: true,
baseClass: "jcrop",
addClass: null,
bgColor: "black",
bgOpacity: 0.6,
bgFade: false,
borderOpacity: 0.4,
handleOpacity: 0.5,
handleSize: null,
aspectRatio: 0,
keySupport: true,
createHandles: ["n", "s", "e", "w", "nw", "ne", "se", "sw"],
createDragbars: ["n", "s", "e", "w"],
createBorders: ["n", "s", "e", "w"],
drawBorders: true,
dragEdges: true,
fixedSupport: true,
touchSupport: null,
shade: null,
boxWidth: 0,
boxHeight: 0,
boundary: 2,
fadeTime: 400,
animationDelay: 20,
swingSpeed: 3,
minSelect: [0, 0],
maxSize: [0, 0],
minSize: [0, 0],
onChange: function () {},
onSelect: function () {},
onDblClick: function () {},
onRelease: function () {},
};
})(jQuery);
!(function () {
var q = null;
window.PR_SHOULD_USE_CONTINUATION = !0;
(function () {
function S(a) {
function d(e) {
var b = e.charCodeAt(0);
if (b !== 92) return b;
var a = e.charAt(1);
return (b = r[a])
? b
: "0" <= a && a <= "7"
? parseInt(e.substring(1), 8)
: a === "u" || a === "x"
? parseInt(e.substring(2), 16)
: e.charCodeAt(1);
}
function g(e) {
if (e < 32) return (e < 16 ? "\\x0" : "\\x") + e.toString(16);
e = String.fromCharCode(e);
return e === "\\" || e === "-" || e === "]" || e === "^"
? "\\" + e
: e;
}
function b(e) {
var b = e
.substring(1, e.length - 1)
.match(
/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g
),
e = [],
a = b[0] === "^",
c = ["["];
a && c.push("^");
for (var a = a ? 1 : 0, f = b.length; a < f; ++a) {
var h = b[a];
if (/\\[bdsw]/i.test(h)) c.push(h);
else {
var h = d(h),
l;
a + 2 < f && "-" === b[a + 1]
? ((l = d(b[a + 2])), (a += 2))
: (l = h);
e.push([h, l]);
l < 65 ||
h > 122 ||
(l < 65 ||
h > 90 ||
e.push([
Math.max(65, h) | 32,
Math.min(l, 90) | 32,
]),
l < 97 ||
h > 122 ||
e.push([
Math.max(97, h) & -33,
Math.min(l, 122) & -33,
]));
}
}
e.sort(function (e, a) {
return e[0] - a[0] || a[1] - e[1];
});
b = [];
f = [];
for (a = 0; a < e.length; ++a)
(h = e[a]),
h[0] <= f[1] + 1
? (f[1] = Math.max(f[1], h[1]))
: b.push((f = h));
for (a = 0; a < b.length; ++a)
(h = b[a]),
c.push(g(h[0])),
h[1] > h[0] &&
(h[1] + 1 > h[0] && c.push("-"), c.push(g(h[1])));
c.push("]");
return c.join("");
}
function s(e) {
for (
var a = e.source.match(
/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g
),
c = a.length,
d = [],
f = 0,
h = 0;
f < c;
++f
) {
var l = a[f];
l === "("
? ++h
: "\\" === l.charAt(0) &&
(l = +l.substring(1)) &&
(l <= h ? (d[l] = -1) : (a[f] = g(l)));
}
for (f = 1; f < d.length; ++f) -1 === d[f] && (d[f] = ++x);
for (h = f = 0; f < c; ++f)
(l = a[f]),
l === "("
? (++h, d[h] || (a[f] = "(?:"))
: "\\" === l.charAt(0) &&
(l = +l.substring(1)) &&
l <= h &&
(a[f] = "\\" + d[l]);
for (f = 0; f < c; ++f)
"^" === a[f] && "^" !== a[f + 1] && (a[f] = "");
if (e.ignoreCase && m)
for (f = 0; f < c; ++f)
(l = a[f]),
(e = l.charAt(0)),
l.length >= 2 && e === "["
? (a[f] = b(l))
: e !== "\\" &&
(a[f] = l.replace(/[A-Za-z]/g, function (a) {
a = a.charCodeAt(0);
return (
"[" +
String.fromCharCode(a & -33, a | 32) +
"]"
);
}));
return a.join("");
}
for (var x = 0, m = !1, j = !1, k = 0, c = a.length; k < c; ++k) {
var i = a[k];
if (i.ignoreCase) j = !0;
else if (
/[a-z]/i.test(
i.source.replace(
/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,
""
)
)
) {
m = !0;
j = !1;
break;
}
}
for (
var r = { b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 },
n = [],
k = 0,
c = a.length;
k < c;
++k
) {
i = a[k];
if (i.global || i.multiline) throw Error("" + i);
n.push("(?:" + s(i) + ")");
}
return RegExp(n.join("|"), j ? "gi" : "g");
}
function T(a, d) {
function g(a) {
var c = a.nodeType;
if (c == 1) {
if (!b.test(a.className)) {
for (c = a.firstChild; c; c = c.nextSibling) g(c);
c = a.nodeName.toLowerCase();
if ("br" === c || "li" === c)
(s[j] = "\n"),
(m[j << 1] = x++),
(m[(j++ << 1) | 1] = a);
}
} else if (c == 3 || c == 4)
(c = a.nodeValue),
c.length &&
((c = d
? c.replace(/\r\n?/g, "\n")
: c.replace(/[\t\n\r ]+/g, " ")),
(s[j] = c),
(m[j << 1] = x),
(x += c.length),
(m[(j++ << 1) | 1] = a));
}
var b = /(?:^|\s)nocode(?:\s|$)/,
s = [],
x = 0,
m = [],
j = 0;
g(a);
return { a: s.join("").replace(/\n$/, ""), d: m };
}
function H(a, d, g, b) {
d && ((a = { a: d, e: a }), g(a), b.push.apply(b, a.g));
}
function U(a) {
for (var d = void 0, g = a.firstChild; g; g = g.nextSibling)
var b = g.nodeType,
d =
b === 1
? d
? a
: g
: b === 3
? V.test(g.nodeValue)
? a
: d
: d;
return d === a ? void 0 : d;
}
function C(a, d) {
function g(a) {
for (
var j = a.e,
k = [j, "pln"],
c = 0,
i = a.a.match(s) || [],
r = {},
n = 0,
e = i.length;
n < e;
++n
) {
var z = i[n],
w = r[z],
t = void 0,
f;
if (typeof w === "string") f = !1;
else {
var h = b[z.charAt(0)];
if (h) (t = z.match(h[1])), (w = h[0]);
else {
for (f = 0; f < x; ++f)
if (((h = d[f]), (t = z.match(h[1])))) {
w = h[0];
break;
}
t || (w = "pln");
}
if (
(f =
w.length >= 5 &&
"lang-" === w.substring(0, 5)) &&
!(t && typeof t[1] === "string")
)
(f = !1), (w = "src");
f || (r[z] = w);
}
h = c;
c += z.length;
if (f) {
f = t[1];
var l = z.indexOf(f),
B = l + f.length;
t[2] &&
((B = z.length - t[2].length), (l = B - f.length));
w = w.substring(5);
H(j + h, z.substring(0, l), g, k);
H(j + h + l, f, I(w, f), k);
H(j + h + B, z.substring(B), g, k);
} else k.push(j + h, w);
}
a.g = k;
}
var b = {},
s;
(function () {
for (
var g = a.concat(d), j = [], k = {}, c = 0, i = g.length;
c < i;
++c
) {
var r = g[c],
n = r[3];
if (n)
for (var e = n.length; --e >= 0; ) b[n.charAt(e)] = r;
r = r[1];
n = "" + r;
k.hasOwnProperty(n) || (j.push(r), (k[n] = q));
}
j.push(/[\S\s]/);
s = S(j);
})();
var x = d.length;
return g;
}
function v(a) {
var d = [],
g = [];
a.tripleQuotedStrings
? d.push([
"str",
/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,
q,
"'\"",
])
: a.multiLineStrings
? d.push([
"str",
/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,
"'\"`",
])
: d.push([
"str",
/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,
q,
"\"'",
]);
a.verbatimStrings && g.push(["str", /^@"(?:[^"]|"")*(?:"|$)/, q]);
var b = a.hashComments;
b &&
(a.cStyleComments
? (b > 1
? d.push([
"com",
/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,
q,
"#",
])
: d.push([
"com",
/^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\n\r]*)/,
q,
"#",
]),
g.push([
"str",
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
q,
]))
: d.push(["com", /^#[^\n\r]*/, q, "#"]));
a.cStyleComments &&
(g.push(["com", /^\/\/[^\n\r]*/, q]),
g.push(["com", /^\/\*[\S\s]*?(?:\*\/|$)/, q]));
if ((b = a.regexLiterals)) {
var s = (b = b > 1 ? "" : "\n\r") ? "." : "[\\S\\s]";
g.push([
"lang-regex",
RegExp(
"^(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*(" +
("/(?=[^/*" +
b +
"])(?:[^/\\x5B\\x5C" +
b +
"]|\\x5C" +
s +
"|\\x5B(?:[^\\x5C\\x5D" +
b +
"]|\\x5C" +
s +
")*(?:\\x5D|$))+/") +
")"
),
]);
}
(b = a.types) && g.push(["typ", b]);
b = ("" + a.keywords).replace(/^ | $/g, "");
b.length &&
g.push([
"kwd",
RegExp("^(?:" + b.replace(/[\s,]+/g, "|") + ")\\b"),
q,
]);
d.push(["pln", /^\s+/, q, " \r\n\t\u00a0"]);
b = "^.[^\\s\\w.$@'\"`/\\\\]*";
a.regexLiterals && (b += "(?!s*/)");
g.push(
["lit", /^@[$_a-z][\w$@]*/i, q],
["typ", /^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/, q],
["pln", /^[$_a-z][\w$@]*/i, q],
[
"lit",
/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,
q,
"0123456789",
],
["pln", /^\\[\S\s]?/, q],
["pun", RegExp(b), q]
);
return C(d, g);
}
function J(a, d, g) {
function b(a) {
var c = a.nodeType;
if (c == 1 && !x.test(a.className))
if ("br" === a.nodeName)
s(a), a.parentNode && a.parentNode.removeChild(a);
else for (a = a.firstChild; a; a = a.nextSibling) b(a);
else if ((c == 3 || c == 4) && g) {
var d = a.nodeValue,
i = d.match(m);
if (i)
(c = d.substring(0, i.index)),
(a.nodeValue = c),
(d = d.substring(i.index + i[0].length)) &&
a.parentNode.insertBefore(
j.createTextNode(d),
a.nextSibling
),
s(a),
c || a.parentNode.removeChild(a);
}
}
function s(a) {
function b(a, c) {
var d = c ? a.cloneNode(!1) : a,
e = a.parentNode;
if (e) {
var e = b(e, 1),
g = a.nextSibling;
e.appendChild(d);
for (var i = g; i; i = g)
(g = i.nextSibling), e.appendChild(i);
}
return d;
}
for (; !a.nextSibling; ) if (((a = a.parentNode), !a)) return;
for (
var a = b(a.nextSibling, 0), d;
(d = a.parentNode) && d.nodeType === 1;
)
a = d;
c.push(a);
}
for (
var x = /(?:^|\s)nocode(?:\s|$)/,
m = /\r\n?|\n/,
j = a.ownerDocument,
k = j.createElement("li");
a.firstChild;
)
k.appendChild(a.firstChild);
for (var c = [k], i = 0; i < c.length; ++i) b(c[i]);
d === (d | 0) && c[0].setAttribute("value", d);
var r = j.createElement("ol");
r.className = "linenums";
for (
var d = Math.max(0, (d - 1) | 0) || 0, i = 0, n = c.length;
i < n;
++i
)
(k = c[i]),
(k.className = "L" + ((i + d) % 10)),
k.firstChild || k.appendChild(j.createTextNode("\u00a0")),
r.appendChild(k);
a.appendChild(r);
}
function p(a, d) {
for (var g = d.length; --g >= 0; ) {
var b = d[g];
F.hasOwnProperty(b)
? D.console &&
console.warn("cannot override language handler %s", b)
: (F[b] = a);
}
}
function I(a, d) {
if (!a || !F.hasOwnProperty(a))
a = /^\s*</.test(d) ? "default-markup" : "default-code";
return F[a];
}
function K(a) {
var d = a.h;
try {
var g = T(a.c, a.i),
b = g.a;
a.a = b;
a.d = g.d;
a.e = 0;
I(d, b)(a);
var s = /\bMSIE\s(\d+)/.exec(navigator.userAgent),
s = s && +s[1] <= 8,
d = /\n/g,
x = a.a,
m = x.length,
g = 0,
j = a.d,
k = j.length,
b = 0,
c = a.g,
i = c.length,
r = 0;
c[i] = m;
var n, e;
for (e = n = 0; e < i; )
c[e] !== c[e + 2]
? ((c[n++] = c[e++]), (c[n++] = c[e++]))
: (e += 2);
i = n;
for (e = n = 0; e < i; ) {
for (
var p = c[e], w = c[e + 1], t = e + 2;
t + 2 <= i && c[t + 1] === w;
)
t += 2;
c[n++] = p;
c[n++] = w;
e = t;
}
c.length = n;
var f = a.c,
h;
if (f) (h = f.style.display), (f.style.display = "none");
try {
for (; b < k; ) {
var l = j[b + 2] || m,
B = c[r + 2] || m,
t = Math.min(l, B),
A = j[b + 1],
G;
if (A.nodeType !== 1 && (G = x.substring(g, t))) {
s && (G = G.replace(d, "\r"));
A.nodeValue = G;
var L = A.ownerDocument,
o = L.createElement("span");
o.className = c[r + 1];
var v = A.parentNode;
v.replaceChild(o, A);
o.appendChild(A);
g < l &&
((j[b + 1] = A = L.createTextNode(
x.substring(t, l)
)),
v.insertBefore(A, o.nextSibling));
}
g = t;
g >= l && (b += 2);
g >= B && (r += 2);
}
} finally {
if (f) f.style.display = h;
}
} catch (u) {
D.console && console.log((u && u.stack) || u);
}
}
var D = window,
y = ["break,continue,do,else,for,if,return,while"],
E = [
[
y,
"auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile",
],
"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof",
],
M = [
E,
"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where",
],
N = [
E,
"abstract,assert,boolean,byte,extends,final,finally,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient",
],
O = [
N,
"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,internal,into,is,let,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var,virtual,where",
],
E = [
E,
"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN",
],
P = [
y,
"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None",
],
Q = [
y,
"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END",
],
W = [
y,
"as,assert,const,copy,drop,enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv,pub,pure,ref,self,static,struct,true,trait,type,unsafe,use",
],
y = [
y,
"case,done,elif,esac,eval,fi,function,in,local,set,then,until",
],
R = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/,
V = /\S/,
X = v({
keywords: [
M,
O,
E,
"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",
P,
Q,
y,
],
hashComments: !0,
cStyleComments: !0,
multiLineStrings: !0,
regexLiterals: !0,
}),
F = {};
p(X, ["default-code"]);
p(
C(
[],
[
["pln", /^[^<?]+/],
["dec", /^<!\w[^>]*(?:>|$)/],
["com", /^<\!--[\S\s]*?(?:--\>|$)/],
["lang-", /^<\?([\S\s]+?)(?:\?>|$)/],
["lang-", /^<%([\S\s]+?)(?:%>|$)/],
["pun", /^(?:<[%?]|[%?]>)/],
["lang-", /^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],
[
"lang-js",
/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i,
],
[
"lang-css",
/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i,
],
["lang-in.tag", /^(<\/?[a-z][^<>]*>)/i],
]
),
["default-markup", "htm", "html", "mxml", "xhtml", "xml", "xsl"]
);
p(
C(
[
["pln", /^\s+/, q, " \t\r\n"],
["atv", /^(?:"[^"]*"?|'[^']*'?)/, q, "\"'"],
],
[
["tag", /^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],
["atn", /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
["lang-uq.val", /^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],
["pun", /^[/<->]+/],
["lang-js", /^on\w+\s*=\s*"([^"]+)"/i],
["lang-js", /^on\w+\s*=\s*'([^']+)'/i],
["lang-js", /^on\w+\s*=\s*([^\s"'>]+)/i],
["lang-css", /^style\s*=\s*"([^"]+)"/i],
["lang-css", /^style\s*=\s*'([^']+)'/i],
["lang-css", /^style\s*=\s*([^\s"'>]+)/i],
]
),
["in.tag"]
);
p(C([], [["atv", /^[\S\s]+/]]), ["uq.val"]);
p(v({ keywords: M, hashComments: !0, cStyleComments: !0, types: R }), [
"c",
"cc",
"cpp",
"cxx",
"cyc",
"m",
]);
p(v({ keywords: "null,true,false" }), ["json"]);
p(
v({
keywords: O,
hashComments: !0,
cStyleComments: !0,
verbatimStrings: !0,
types: R,
}),
["cs"]
);
p(v({ keywords: N, cStyleComments: !0 }), ["java"]);
p(v({ keywords: y, hashComments: !0, multiLineStrings: !0 }), [
"bash",
"bsh",
"csh",
"sh",
]);
p(
v({
keywords: P,
hashComments: !0,
multiLineStrings: !0,
tripleQuotedStrings: !0,
}),
["cv", "py", "python"]
);
p(
v({
keywords:
"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",
hashComments: !0,
multiLineStrings: !0,
regexLiterals: 2,
}),
["perl", "pl", "pm"]
);
p(
v({
keywords: Q,
hashComments: !0,
multiLineStrings: !0,
regexLiterals: !0,
}),
["rb", "ruby"]
);
p(v({ keywords: E, cStyleComments: !0, regexLiterals: !0 }), [
"javascript",
"js",
]);
p(
v({
keywords:
"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,throw,true,try,unless,until,when,while,yes",
hashComments: 3,
cStyleComments: !0,
multilineStrings: !0,
tripleQuotedStrings: !0,
regexLiterals: !0,
}),
["coffee"]
);
p(v({ keywords: W, cStyleComments: !0, multilineStrings: !0 }), [
"rc",
"rs",
"rust",
]);
p(C([], [["str", /^[\S\s]+/]]), ["regex"]);
var Y = (D.PR = {
createSimpleLexer: C,
registerLangHandler: p,
sourceDecorator: v,
PR_ATTRIB_NAME: "atn",
PR_ATTRIB_VALUE: "atv",
PR_COMMENT: "com",
PR_DECLARATION: "dec",
PR_KEYWORD: "kwd",
PR_LITERAL: "lit",
PR_NOCODE: "nocode",
PR_PLAIN: "pln",
PR_PUNCTUATION: "pun",
PR_SOURCE: "src",
PR_STRING: "str",
PR_TAG: "tag",
PR_TYPE: "typ",
prettyPrintOne: (D.prettyPrintOne = function (a, d, g) {
var b = document.createElement("div");
b.innerHTML = "<pre>" + a + "</pre>";
b = b.firstChild;
g && J(b, g, !0);
K({ h: d, j: g, c: b, i: 1 });
return b.innerHTML;
}),
prettyPrint: (D.prettyPrint = function (a, d) {
function g() {
for (
var b = D.PR_SHOULD_USE_CONTINUATION
? c.now() + 250
: Infinity;
i < p.length && c.now() < b;
i++
) {
for (
var d = p[i], j = h, k = d;
(k = k.previousSibling);
) {
var m = k.nodeType,
o = (m === 7 || m === 8) && k.nodeValue;
if (
o
? !/^\??prettify\b/.test(o)
: m !== 3 || /\S/.test(k.nodeValue)
)
break;
if (o) {
j = {};
o.replace(/\b(\w+)=([\w%+\-.:]+)/g, function (
a,
b,
c
) {
j[b] = c;
});
break;
}
}
k = d.className;
if ((j !== h || e.test(k)) && !v.test(k)) {
m = !1;
for (o = d.parentNode; o; o = o.parentNode)
if (
f.test(o.tagName) &&
o.className &&
e.test(o.className)
) {
m = !0;
break;
}
if (!m) {
d.className += " prettyprinted";
m = j.lang;
if (!m) {
var m = k.match(n),
y;
if (!m && (y = U(d)) && t.test(y.tagName))
m = y.className.match(n);
m && (m = m[1]);
}
if (w.test(d.tagName)) o = 1;
else
var o = d.currentStyle,
u = s.defaultView,
o =
(o = o
? o.whiteSpace
: u && u.getComputedStyle
? u
.getComputedStyle(d, q)
.getPropertyValue(
"white-space"
)
: 0) &&
"pre" === o.substring(0, 3);
u = j.linenums;
if (!(u = u === "true" || +u))
u = (u = k.match(/\blinenums\b(?::(\d+))?/))
? u[1] && u[1].length
? +u[1]
: !0
: !1;
u && J(d, u, o);
r = { h: m, c: d, j: u, i: o };
K(r);
}
}
}
i < p.length
? setTimeout(g, 250)
: "function" === typeof a && a();
}
for (
var b = d || document.body,
s = b.ownerDocument || document,
b = [
b.getElementsByTagName("pre"),
b.getElementsByTagName("code"),
b.getElementsByTagName("xmp"),
],
p = [],
m = 0;
m < b.length;
++m
)
for (var j = 0, k = b[m].length; j < k; ++j)
p.push(b[m][j]);
var b = q,
c = Date;
c.now ||
(c = {
now: function () {
return +new Date();
},
});
var i = 0,
r,
n = /\blang(?:uage)?-([\w.]+)(?!\S)/,
e = /\bprettyprint\b/,
v = /\bprettyprinted\b/,
w = /pre|xmp/i,
t = /^code$/i,
f = /^(?:pre|code|xmp)$/i,
h = {};
g();
}),
});
typeof define === "function" &&
define.amd &&
define("google-code-prettify", [], function () {
return Y;
});
})();
})() +
(function ($) {
"use strict";
if ($.oc.mediaManager === undefined) $.oc.mediaManager = {};
var Base = $.oc.foundation.base,
BaseProto = Base.prototype;
var MediaManagerPopup = function (options) {
this.$popupRootElement = null;
this.options = $.extend({}, MediaManagerPopup.DEFAULTS, options);
Base.call(this);
this.init();
this.show();
};
MediaManagerPopup.prototype = Object.create(BaseProto);
MediaManagerPopup.prototype.constructor = MediaManagerPopup;
MediaManagerPopup.prototype.dispose = function () {
this.unregisterHandlers();
this.$popupRootElement.remove();
this.$popupRootElement = null;
this.$popupElement = null;
BaseProto.dispose.call(this);
};
MediaManagerPopup.prototype.init = function () {
if (this.options.alias === undefined)
throw new Error(
'Media Manager popup option "alias" is not set.'
);
this.$popupRootElement = $("<div/>");
this.registerHandlers();
};
MediaManagerPopup.prototype.registerHandlers = function () {
this.$popupRootElement.one(
"hide.oc.popup",
this.proxy(this.onPopupHidden)
);
this.$popupRootElement.one(
"shown.oc.popup",
this.proxy(this.onPopupShown)
);
};
MediaManagerPopup.prototype.unregisterHandlers = function () {
this.$popupElement.off(
"popupcommand",
this.proxy(this.onPopupCommand)
);
this.$popupRootElement.off(
"popupcommand",
this.proxy(this.onPopupCommand)
);
};
MediaManagerPopup.prototype.show = function () {
var data = {
bottomToolbar: this.options.bottomToolbar ? 1 : 0,
cropAndInsertButton: this.options.cropAndInsertButton ? 1 : 0,
};
this.$popupRootElement.popup({
extraData: data,
size: "adaptive",
adaptiveHeight: true,
handler: this.options.alias + "::onLoadPopup",
});
};
MediaManagerPopup.prototype.hide = function () {
if (this.$popupElement)
this.$popupElement.trigger("close.oc.popup");
};
MediaManagerPopup.prototype.getMediaManagerElement = function () {
return this.$popupElement.find('[data-control="media-manager"]');
};
MediaManagerPopup.prototype.insertMedia = function () {
var items = this.getMediaManagerElement().mediaManager(
"getSelectedItems"
);
if (this.options.onInsert !== undefined)
this.options.onInsert.call(this, items);
};
MediaManagerPopup.prototype.insertCroppedImage = function (imageItem) {
if (this.options.onInsert !== undefined)
this.options.onInsert.call(this, [imageItem]);
};
MediaManagerPopup.prototype.onPopupHidden = function (
event,
element,
popup
) {
var mediaManager = this.getMediaManagerElement();
mediaManager.mediaManager("dispose");
mediaManager.remove();
$(document).trigger("mousedown");
this.dispose();
if (this.options.onClose !== undefined)
this.options.onClose.call(this);
};
MediaManagerPopup.prototype.onPopupShown = function (
event,
element,
popup
) {
this.$popupElement = popup;
this.$popupElement.on(
"popupcommand",
this.proxy(this.onPopupCommand)
);
this.getMediaManagerElement().mediaManager("selectFirstItem");
};
MediaManagerPopup.prototype.onPopupCommand = function (
ev,
command,
param
) {
switch (command) {
case "insert":
this.insertMedia();
break;
case "insert-cropped":
this.insertCroppedImage(param);
break;
}
return false;
};
MediaManagerPopup.DEFAULTS = {
alias: undefined,
bottomToolbar: true,
cropAndInsertButton: false,
onInsert: undefined,
onClose: undefined,
};
$.oc.mediaManager.popup = MediaManagerPopup;
})(window.jQuery);
if ($.oc === undefined) $.oc = {};
if ($.oc.langMessages === undefined) $.oc.langMessages = {};
$.oc.lang = (function (lang, messages) {
lang.load = function (locale) {
if (messages[locale] === undefined) {
messages[locale] = {};
}
lang.loadedMessages = messages[locale];
};
lang.get = function (name, defaultValue) {
if (!name) return;
var result = lang.loadedMessages;
if (!defaultValue) defaultValue = name;
$.each(name.split("."), function (index, value) {
if (result[value] === undefined) {
result = defaultValue;
return false;
}
result = result[value];
});
return result;
};
if (lang.locale === undefined) {
lang.locale = $("html").attr("lang") || "en";
}
if (lang.loadedMessages === undefined) {
lang.load(lang.locale);
}
return lang;
})($.oc.lang || {}, $.oc.langMessages);
(function ($) {
if ($.oc === undefined) $.oc = {};
$.oc.alert = function alert(message) {
swal({ title: message, confirmButtonClass: "btn-primary" });
};
$.oc.confirm = function confirm(message, callback) {
swal(
{
title: message,
showCancelButton: true,
confirmButtonClass: "btn-primary",
},
callback
);
};
})(jQuery);
$(window).on("ajaxErrorMessage", function (event, message) {
if (!message) return;
$.oc.alert(message);
event.preventDefault();
});
$(window).on("ajaxConfirmMessage", function (event, message) {
if (!message) return;
$.oc.confirm(message, function (isConfirm) {
isConfirm ? event.promise.resolve() : event.promise.reject();
});
event.preventDefault();
return true;
});
$(document).ready(function () {
if (!window.swal) return;
var swal = window.swal;
window.sweetAlert = window.swal = function (message, callback) {
if (typeof message === "object") {
message.confirmButtonText =
message.confirmButtonText ||
$.oc.lang.get("alert.confirm_button_text");
message.cancelButtonText =
message.cancelButtonText ||
$.oc.lang.get("alert.cancel_button_text");
} else {
message = {
title: message,
confirmButtonText: $.oc.lang.get("alert.confirm_button_text"),
cancelButtonText: $.oc.lang.get("alert.cancel_button_text"),
};
}
swal(message, callback);
};
}) +
(function ($) {
"use strict";
var Base = $.oc.foundation.base,
BaseProto = Base.prototype;
var Scrollpad = function (element, options) {
this.$el = $(element);
this.scrollbarElement = null;
this.dragHandleElement = null;
this.scrollContentElement = null;
this.contentElement = null;
this.options = options;
this.scrollbarSize = null;
this.updateScrollbarTimer = null;
this.dragOffset = null;
Base.call(this);
this.init();
$.oc.foundation.controlUtils.markDisposable(element);
};
Scrollpad.prototype = Object.create(BaseProto);
Scrollpad.prototype.constructor = Scrollpad;
Scrollpad.prototype.dispose = function () {
this.unregisterHandlers();
this.$el.get(0).removeChild(this.scrollbarElement);
this.$el.removeData("oc.scrollpad");
this.$el = null;
this.scrollbarElement = null;
this.dragHandleElement = null;
this.scrollContentElement = null;
this.contentElement = null;
BaseProto.dispose.call(this);
};
Scrollpad.prototype.scrollToStart = function () {
var scrollAttr =
this.options.direction == "vertical"
? "scrollTop"
: "scrollLeft";
this.scrollContentElement[scrollAttr] = 0;
};
Scrollpad.prototype.update = function () {
this.updateScrollbarSize();
};
Scrollpad.prototype.init = function () {
this.build();
this.setScrollContentSize();
this.registerHandlers();
};
Scrollpad.prototype.build = function () {
var el = this.$el.get(0);
this.scrollContentElement = el.children[0];
this.contentElement = this.scrollContentElement.children[0];
this.$el.prepend(
'<div class="scrollpad-scrollbar"><div class="drag-handle"></div></div>'
);
this.scrollbarElement = el.querySelector(".scrollpad-scrollbar");
this.dragHandleElement = el.querySelector(
".scrollpad-scrollbar > .drag-handle"
);
};
Scrollpad.prototype.registerHandlers = function () {
this.$el.on("mouseenter", this.proxy(this.onMouseEnter));
this.$el.on("mouseleave", this.proxy(this.onMouseLeave));
this.$el.one("dispose-control", this.proxy(this.dispose));
this.scrollContentElement.addEventListener(
"scroll",
this.proxy(this.onScroll)
);
this.dragHandleElement.addEventListener(
"mousedown",
this.proxy(this.onStartDrag)
);
};
Scrollpad.prototype.unregisterHandlers = function () {
this.$el.off("mouseenter", this.proxy(this.onMouseEnter));
this.$el.off("mouseleave", this.proxy(this.onMouseLeave));
this.$el.off("dispose-control", this.proxy(this.dispose));
this.scrollContentElement.removeEventListener(
"scroll",
this.proxy(this.onScroll)
);
this.dragHandleElement.removeEventListener(
"mousedown",
this.proxy(this.onStartDrag)
);
document.removeEventListener(
"mousemove",
this.proxy(this.onMouseMove)
);
document.removeEventListener("mouseup", this.proxy(this.onEndDrag));
};
Scrollpad.prototype.setScrollContentSize = function () {
var scrollbarSize = this.getScrollbarSize();
if (this.options.direction == "vertical")
this.scrollContentElement.setAttribute(
"style",
"margin-right: -" + scrollbarSize + "px"
);
else
this.scrollContentElement.setAttribute(
"style",
"margin-bottom: -" + scrollbarSize + "px"
);
};
Scrollpad.prototype.getScrollbarSize = function () {
if (this.scrollbarSize !== null) return this.scrollbarSize;
var testerElement = document.createElement("div");
testerElement.setAttribute(
"class",
"scrollpad-scrollbar-size-tester"
);
testerElement.appendChild(document.createElement("div"));
document.body.appendChild(testerElement);
var width = testerElement.offsetWidth,
innerWidth = testerElement.querySelector("div").offsetWidth;
document.body.removeChild(testerElement);
if (
width === innerWidth &&
navigator.userAgent.toLowerCase().indexOf("firefox") > -1
)
return (this.scrollbarSize = 17);
return (this.scrollbarSize = width - innerWidth);
};
Scrollpad.prototype.updateScrollbarSize = function () {
this.scrollbarElement.removeAttribute("data-hidden");
var contentSize =
this.options.direction == "vertical"
? this.contentElement.scrollHeight
: this.contentElement.scrollWidth,
scrollOffset =
this.options.direction == "vertical"
? this.scrollContentElement.scrollTop
: this.scrollContentElement.scrollLeft,
scrollbarSize =
this.options.direction == "vertical"
? this.scrollbarElement.offsetHeight
: this.scrollbarElement.offsetWidth,
scrollbarRatio = scrollbarSize / contentSize,
handleOffset = Math.round(scrollbarRatio * scrollOffset) + 2,
handleSize =
Math.floor(scrollbarRatio * (scrollbarSize - 2)) - 2;
if (scrollbarSize < contentSize) {
if (this.options.direction == "vertical")
this.dragHandleElement.setAttribute(
"style",
"top: " +
handleOffset +
"px; height: " +
handleSize +
"px"
);
else
this.dragHandleElement.setAttribute(
"style",
"left: " +
handleOffset +
"px; width: " +
handleSize +
"px"
);
this.scrollbarElement.removeAttribute("data-hidden");
} else this.scrollbarElement.setAttribute("data-hidden", true);
};
Scrollpad.prototype.displayScrollbar = function () {
this.clearUpdateScrollbarTimer();
this.updateScrollbarSize();
this.scrollbarElement.setAttribute("data-visible", "true");
};
Scrollpad.prototype.hideScrollbar = function () {
this.scrollbarElement.removeAttribute("data-visible");
};
Scrollpad.prototype.clearUpdateScrollbarTimer = function () {
if (this.updateScrollbarTimer === null) return;
clearTimeout(this.updateScrollbarTimer);
this.updateScrollbarTimer = null;
};
Scrollpad.prototype.onMouseEnter = function () {
this.displayScrollbar();
};
Scrollpad.prototype.onMouseLeave = function () {
this.hideScrollbar();
};
Scrollpad.prototype.onScroll = function () {
if (this.updateScrollbarTimer !== null) return;
this.updateScrollbarTimer = setTimeout(
this.proxy(this.displayScrollbar),
10
);
};
Scrollpad.prototype.onStartDrag = function (ev) {
$.oc.foundation.event.stop(ev);
var pageCoords = $.oc.foundation.event.pageCoordinates(ev),
eventOffset =
this.options.direction == "vertical"
? pageCoords.y
: pageCoords.x,
handleCoords = $.oc.foundation.element.absolutePosition(
this.dragHandleElement
),
handleOffset =
this.options.direction == "vertical"
? handleCoords.top
: handleCoords.left;
this.dragOffset = eventOffset - handleOffset;
document.addEventListener(
"mousemove",
this.proxy(this.onMouseMove)
);
document.addEventListener("mouseup", this.proxy(this.onEndDrag));
};
Scrollpad.prototype.onMouseMove = function (ev) {
$.oc.foundation.event.stop(ev);
var eventCoordsAttr =
this.options.direction == "vertical" ? "y" : "x",
elementCoordsAttr =
this.options.direction == "vertical" ? "top" : "left",
offsetAttr =
this.options.direction == "vertical"
? "offsetHeight"
: "offsetWidth",
scrollAttr =
this.options.direction == "vertical"
? "scrollTop"
: "scrollLeft";
var eventOffset = $.oc.foundation.event.pageCoordinates(ev)[
eventCoordsAttr
],
scrollbarOffset = $.oc.foundation.element.absolutePosition(
this.scrollbarElement
)[elementCoordsAttr],
dragPos = eventOffset - scrollbarOffset - this.dragOffset,
scrollbarSize = this.scrollbarElement[offsetAttr],
contentSize = this.contentElement[offsetAttr],
dragPerc = dragPos / scrollbarSize;
if (dragPerc > 1) dragPerc = 1;
var scrollPos = dragPerc * contentSize;
this.scrollContentElement[scrollAttr] = scrollPos;
};
Scrollpad.prototype.onEndDrag = function (ev) {
document.removeEventListener(
"mousemove",
this.proxy(this.onMouseMove)
);
document.removeEventListener("mouseup", this.proxy(this.onEndDrag));
};
Scrollpad.DEFAULTS = { direction: "vertical" };
var old = $.fn.scrollpad;
$.fn.scrollpad = function (option) {
var args = Array.prototype.slice.call(arguments, 1),
result = undefined;
this.each(function () {
var $this = $(this);
var data = $this.data("oc.scrollpad");
var options = $.extend(
{},
Scrollpad.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data(
"oc.scrollpad",
(data = new Scrollpad(this, options))
);
if (typeof option == "string")
result = data[option].apply(data, args);
if (typeof result != "undefined") return false;
});
return result ? result : this;
};
$.fn.scrollpad.Constructor = Scrollpad;
$.fn.scrollpad.noConflict = function () {
$.fn.scrollpad = old;
return this;
};
$(document).on("render", function () {
$("div[data-control=scrollpad]").scrollpad();
});
})(window.jQuery);
+(function ($) {
"use strict";
var VerticalMenu = function (element, toggle, options) {
this.$el = $(element);
this.body = $("body");
this.toggle = $(toggle);
this.options = options || {};
this.options = $.extend({}, VerticalMenu.DEFAULTS, this.options);
this.wrapper = $(this.options.contentWrapper);
this.breakpoint = options.breakpoint;
this.menuPanel = $("<div></div>")
.appendTo("body")
.addClass(this.options.collapsedMenuClass)
.css("width", 0);
this.menuContainer = $("<div></div>")
.appendTo(this.menuPanel)
.css("display", "none");
this.menuElement = this.$el
.clone()
.appendTo(this.menuContainer)
.css("width", "auto");
var self = this;
this.toggle.click(function () {
if (!self.body.hasClass(self.options.bodyMenuOpenClass)) {
var wrapperWidth = self.wrapper.outerWidth();
self.menuElement.dragScroll("goToStart");
self.wrapper.css({
position: "absolute",
"min-width": self.wrapper.width(),
height: "100%",
});
self.body.addClass(self.options.bodyMenuOpenClass);
self.menuContainer.css("display", "block");
self.wrapper.animate(
{ left: self.options.menuWidth },
{ duration: 200, queue: false }
);
self.menuPanel.animate(
{ width: self.options.menuWidth },
{
duration: 200,
queue: false,
complete: function () {
self.menuElement.css(
"width",
self.options.menuWidth
);
},
}
);
} else {
closeMenu();
}
return false;
});
this.wrapper.click(function () {
if (self.body.hasClass(self.options.bodyMenuOpenClass)) {
closeMenu();
return false;
}
});
$(window).resize(function () {
if (self.body.hasClass(self.options.bodyMenuOpenClass)) {
if ($(window).width() > self.breakpoint) {
hideMenu();
}
}
});
this.menuElement.dragScroll({
vertical: true,
useNative: true,
start: function () {
self.menuElement.addClass("drag");
},
stop: function () {
self.menuElement.removeClass("drag");
},
scrollClassContainer: self.menuPanel,
scrollMarkerContainer: self.menuContainer,
});
this.menuElement.on("click", function () {
if (self.menuElement.hasClass("drag")) return false;
});
function hideMenu() {
self.body.removeClass(self.options.bodyMenuOpenClass);
self.wrapper.css({
position: "static",
"min-width": 0,
right: 0,
height: "100%",
});
self.menuPanel.css("width", 0);
self.menuElement.css("width", "auto");
self.menuContainer.css("display", "none");
}
function closeMenu() {
self.wrapper.animate({ left: 0 }, { duration: 200, queue: false });
self.menuPanel.animate(
{ width: 0 },
{ duration: 200, queue: false, complete: hideMenu }
);
self.menuElement.animate(
{ width: 0 },
{ duration: 200, queue: false }
);
}
};
VerticalMenu.DEFAULTS = {
menuWidth: 230,
breakpoint: 769,
bodyMenuOpenClass: "mainmenu-open",
collapsedMenuClass: "mainmenu-collapsed",
contentWrapper: "#layout-canvas",
};
var old = $.fn.verticalMenu;
$.fn.verticalMenu = function (toggleSelector, option) {
return this.each(function () {
var $this = $(this);
var data = $this.data("oc.verticalMenu");
var options = typeof option == "object" && option;
if (!data)
$this.data(
"oc.verticalMenu",
(data = new VerticalMenu(this, toggleSelector, options))
);
if (typeof option == "string") data[option].call($this);
});
};
$.fn.verticalMenu.Constructor = VerticalMenu;
$.fn.verticalMenu.noConflict = function () {
$.fn.verticalMenu = old;
return this;
};
})(window.jQuery);
(function ($) {
$(document).ready(function () {
$("nav.navbar").each(function () {
var navbar = $(this),
nav = $("ul.nav", navbar),
collapseMode = navbar.hasClass("navbar-mode-collapse"),
isMobile = $("html").hasClass("mobile");
nav.verticalMenu($("a.menu-toggle", navbar), {
breakpoint: collapseMode ? Infinity : 769,
});
$("li.with-tooltip:not(.active) > a", navbar)
.tooltip({
container: "body",
placement: "bottom",
template:
'<div class="tooltip mainmenu-tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
})
.on("show.bs.tooltip", function (e) {
if (isMobile) e.preventDefault();
});
$("[data-calculate-width]", navbar).one(
"oc.widthFixed",
function () {
var dragScroll = $("[data-control=toolbar]", navbar).data(
"oc.dragScroll"
);
if (dragScroll) {
dragScroll.goToElement(
$("ul.nav > li.active", navbar),
undefined,
{ duration: 0 }
);
}
}
);
});
});
})(jQuery);
+(function ($) {
"use strict";
if ($.oc === undefined) $.oc = {};
var SideNav = function (element, options) {
this.options = options;
this.$el = $(element);
this.$list = $("ul", this.$el);
this.$items = $("li", this.$list);
this.init();
};
SideNav.DEFAULTS = { activeClass: "active" };
SideNav.prototype.init = function () {
var self = this;
this.$list.dragScroll({
vertical: true,
useNative: true,
start: function () {
self.$list.addClass("drag");
},
stop: function () {
self.$list.removeClass("drag");
},
scrollClassContainer: self.$el,
scrollMarkerContainer: self.$el,
});
this.$list.on("click", function () {
if (self.$list.hasClass("drag")) {
return false;
}
});
};
SideNav.prototype.unsetActiveItem = function (itemId) {
this.$items.removeClass(this.options.activeClass);
};
SideNav.prototype.setActiveItem = function (itemId) {
if (!itemId) {
return;
}
this.$items
.removeClass(this.options.activeClass)
.filter("[data-menu-item=" + itemId + "]")
.addClass(this.options.activeClass);
};
SideNav.prototype.setCounter = function (itemId, value) {
var $counter = $(
'span.counter[data-menu-id="' + itemId + '"]',
this.$el
);
$counter.removeClass("empty");
$counter.toggleClass("empty", value == 0);
$counter.text(value);
return this;
};
SideNav.prototype.increaseCounter = function (itemId, value) {
var $counter = $(
'span.counter[data-menu-id="' + itemId + '"]',
this.$el
);
var originalValue = parseInt($counter.text());
if (isNaN(originalValue)) originalValue = 0;
var newValue = value + originalValue;
$counter.toggleClass("empty", newValue == 0);
$counter.text(newValue);
return this;
};
SideNav.prototype.dropCounter = function (itemId) {
this.setCounter(itemId, 0);
return this;
};
var old = $.fn.sideNav;
$.fn.sideNav = function (option) {
var args = Array.prototype.slice.call(arguments, 1),
result;
this.each(function () {
var $this = $(this);
var data = $this.data("oc.sideNav");
var options = $.extend(
{},
SideNav.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data("oc.sideNav", (data = new SideNav(this, options)));
if (typeof option == "string")
result = data[option].apply(data, args);
if (typeof result != "undefined") return false;
if ($.oc.sideNav === undefined) $.oc.sideNav = data;
});
return result ? result : this;
};
$.fn.sideNav.Constructor = SideNav;
$.fn.sideNav.noConflict = function () {
$.fn.sideNav = old;
return this;
};
$(document).ready(function () {
$('[data-control="sidenav"]').sideNav();
});
})(window.jQuery);
+(function ($) {
"use strict";
var Base = $.oc.foundation.base,
BaseProto = Base.prototype;
var Scrollbar = function (element, options) {
var $el = (this.$el = $(element)),
el = $el.get(0),
self = this,
options = (this.options = options || {}),
sizeName = (this.sizeName = options.vertical ? "height" : "width"),
isNative = $("html").hasClass("mobile"),
isTouch = (this.isTouch = Modernizr.touchevents),
isScrollable = (this.isScrollable = false),
isLocked = (this.isLocked = false),
eventElementName = options.vertical ? "pageY" : "pageX",
dragStart = 0,
startOffset = 0;
$.oc.foundation.controlUtils.markDisposable(element);
Base.call(this);
this.$el.one("dispose-control", this.proxy(this.dispose));
if (isNative) {
return;
}
this.$scrollbar = $("<div />").addClass("scrollbar-scrollbar");
this.$track = $("<div />")
.addClass("scrollbar-track")
.appendTo(this.$scrollbar);
this.$thumb = $("<div />")
.addClass("scrollbar-thumb")
.appendTo(this.$track);
$el.addClass("drag-scrollbar")
.addClass(options.vertical ? "vertical" : "horizontal")
.prepend(this.$scrollbar);
if (isTouch) {
this.$el.on("touchstart", function (event) {
var touchEvent = event.originalEvent;
if (touchEvent.touches.length == 1) {
startDrag(touchEvent.touches[0]);
event.stopPropagation();
}
});
} else {
this.$thumb.on("mousedown", function (event) {
startDrag(event);
});
this.$track.on("mouseup", function (event) {
moveDrag(event);
});
}
$el.mousewheel(function (event) {
var offset = self.options.vertical
? event.deltaFactor * event.deltaY * -1
: event.deltaFactor * event.deltaX;
return !scrollWheel(offset * self.options.scrollSpeed);
});
$el.on("oc.scrollbar.gotoStart", function (event) {
self.options.vertical ? $el.scrollTop(0) : $el.scrollLeft(0);
self.update();
event.stopPropagation();
});
$(window).on("resize", $.proxy(this.update, this));
$(window).on("oc.updateUi", $.proxy(this.update, this));
function startDrag(event) {
$("body").addClass("drag-noselect");
$el.trigger("oc.scrollStart");
dragStart = event[eventElementName];
startOffset = self.options.vertical
? $el.scrollTop()
: $el.scrollLeft();
if (isTouch) {
$(window).on("touchmove.scrollbar", function (event) {
var touchEvent = event.originalEvent;
if (moveDrag(touchEvent.touches[0])) event.preventDefault();
});
$el.on("touchend.scrollbar", stopDrag);
} else {
$(window).on("mousemove.scrollbar", function (event) {
moveDrag(event);
return false;
});
$(window).on("mouseup.scrollbar", function () {
stopDrag();
return false;
});
}
}
function moveDrag(event) {
self.isLocked = true;
var offset,
dragTo = event[eventElementName];
if (self.isTouch) {
offset = dragStart - dragTo;
} else {
var ratio = self.getCanvasSize() / self.getViewportSize();
offset = (dragTo - dragStart) * ratio;
}
self.options.vertical
? $el.scrollTop(startOffset + offset)
: $el.scrollLeft(startOffset + offset);
self.setThumbPosition();
return self.options.vertical
? el.scrollTop != startOffset
: el.scrollLeft != startOffset;
}
function stopDrag() {
$("body").removeClass("drag-noselect");
$el.trigger("oc.scrollEnd");
$(window).off(".scrollbar");
}
var isWebkit = $(document.documentElement).hasClass("webkit");
function scrollWheel(offset) {
startOffset = self.options.vertical ? el.scrollTop : el.scrollLeft;
$el.trigger("oc.scrollStart");
self.options.vertical
? $el.scrollTop(startOffset + offset)
: $el.scrollLeft(startOffset + offset);
var scrolled = self.options.vertical
? el.scrollTop != startOffset
: el.scrollLeft != startOffset;
self.setThumbPosition();
if (!isWebkit) {
if (self.endScrollTimeout !== undefined) {
clearTimeout(self.endScrollTimeout);
self.endScrollTimeout = undefined;
}
self.endScrollTimeout = setTimeout(function () {
$el.trigger("oc.scrollEnd");
self.endScrollTimeout = undefined;
}, 50);
} else {
$el.trigger("oc.scrollEnd");
}
return scrolled;
}
setTimeout(function () {
self.update();
}, 1);
};
Scrollbar.prototype = Object.create(BaseProto);
Scrollbar.prototype.constructor = Scrollbar;
Scrollbar.prototype.dispose = function () {
this.unregisterHandlers();
BaseProto.dispose.call(this);
};
Scrollbar.prototype.unregisterHandlers = function () {};
Scrollbar.DEFAULTS = {
vertical: true,
scrollSpeed: 2,
animation: true,
start: function () {},
drag: function () {},
stop: function () {},
};
Scrollbar.prototype.update = function () {
if (!this.$scrollbar) return;
this.$scrollbar.hide();
this.setThumbSize();
this.setThumbPosition();
this.$scrollbar.show();
};
Scrollbar.prototype.setThumbSize = function () {
var properties = this.calculateProperties();
this.isScrollable = !(properties.thumbSizeRatio >= 1);
this.$scrollbar.toggleClass("disabled", !this.isScrollable);
if (this.options.vertical) {
this.$track.height(properties.canvasSize);
this.$thumb.height(properties.thumbSize);
} else {
this.$track.width(properties.canvasSize);
this.$thumb.width(properties.thumbSize);
}
};
Scrollbar.prototype.setThumbPosition = function () {
var properties = this.calculateProperties();
if (this.options.vertical)
this.$thumb.css({ top: properties.thumbPosition });
else this.$thumb.css({ left: properties.thumbPosition });
};
Scrollbar.prototype.calculateProperties = function () {
var $el = this.$el,
properties = {};
properties.viewportSize = this.getViewportSize();
properties.canvasSize = this.getCanvasSize();
properties.scrollAmount = this.options.vertical
? $el.scrollTop()
: $el.scrollLeft();
properties.thumbSizeRatio =
properties.viewportSize / properties.canvasSize;
properties.thumbSize =
properties.viewportSize * properties.thumbSizeRatio;
properties.thumbPositionRatio =
properties.scrollAmount /
(properties.canvasSize - properties.viewportSize);
properties.thumbPosition =
(properties.viewportSize - properties.thumbSize) *
properties.thumbPositionRatio +
properties.scrollAmount;
if (isNaN(properties.thumbPosition)) properties.thumbPosition = 0;
return properties;
};
Scrollbar.prototype.getViewportSize = function () {
return this.options.vertical ? this.$el.height() : this.$el.width();
};
Scrollbar.prototype.getCanvasSize = function () {
return this.options.vertical
? this.$el.get(0).scrollHeight
: this.$el.get(0).scrollWidth;
};
Scrollbar.prototype.gotoElement = function (element, callback) {
var $el = $(element);
if (!$el.length) return;
var self = this,
offset = 0,
animated = false,
params = {
duration: 300,
queue: false,
complete: function () {
if (callback !== undefined) callback();
},
};
if (!this.options.vertical) {
offset = $el.get(0).offsetLeft - this.$el.scrollLeft();
if (offset < 0) {
this.$el.animate({ scrollLeft: $el.get(0).offsetLeft }, params);
animated = true;
} else {
offset =
$el.get(0).offsetLeft +
$el.outerWidth() -
(this.$el.scrollLeft() + this.$el.outerWidth());
if (offset > 0) {
this.$el.animate(
{
scrollLeft:
$el.get(0).offsetLeft +
$el.outerWidth() -
this.$el.outerWidth(),
},
params
);
animated = true;
}
}
} else {
offset = $el.get(0).offsetTop - this.$el.scrollTop();
if (this.options.animation) {
if (offset < 0) {
this.$el.animate(
{ scrollTop: $el.get(0).offsetTop },
params
);
animated = true;
} else {
offset =
$el.get(0).offsetTop -
(this.$el.scrollTop() + this.$el.outerHeight());
if (offset > 0) {
this.$el.animate(
{
scrollTop:
$el.get(0).offsetTop +
$el.outerHeight() -
this.$el.outerHeight(),
},
params
);
animated = true;
}
}
} else {
if (offset < 0) {
this.$el.scrollTop($el.get(0).offsetTop);
} else {
offset =
$el.get(0).offsetTop -
(this.$el.scrollTop() + this.$el.outerHeight());
if (offset > 0)
this.$el.scrollTop(
$el.get(0).offsetTop +
$el.outerHeight() -
this.$el.outerHeight()
);
}
}
}
if (!animated && callback !== undefined) callback();
return this;
};
Scrollbar.prototype.dispose = function () {
this.$el = null;
this.$scrollbar = null;
this.$track = null;
this.$thumb = null;
};
var old = $.fn.scrollbar;
$.fn.scrollbar = function (option) {
return this.each(function () {
var $this = $(this);
var data = $this.data("oc.scrollbar");
var options = $.extend(
{},
Scrollbar.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data(
"oc.scrollbar",
(data = new Scrollbar(this, options))
);
if (typeof option == "string") data[option].call($this);
});
};
$.fn.scrollbar.Constructor = Scrollbar;
$.fn.scrollbar.noConflict = function () {
$.fn.scrollbar = old;
return this;
};
$(document).render(function () {
$("[data-control=scrollbar]").scrollbar();
});
})(window.jQuery);
+(function ($) {
"use strict";
var FileList = function (element, options) {
this.options = options;
this.$el = $(element);
this.init();
};
FileList.DEFAULTS = { ignoreItemClick: false };
FileList.prototype.init = function () {
var self = this;
this.$el.on(
"click",
"li.group > h4 > a, li.group > div.group",
function () {
self.toggleGroup($(this).closest("li"));
return false;
}
);
if (!this.options.ignoreItemClick) {
this.$el.on("click", "li.item > a", function (event) {
var e = $.Event("open.oc.list", {
relatedTarget: $(this).parent().get(0),
clickEvent: event,
});
self.$el.trigger(e, this);
return false;
});
}
this.$el.on("ajaxUpdate", $.proxy(this.update, this));
};
FileList.prototype.toggleGroup = function (group) {
var $group = $(group);
$group.attr("data-status") == "expanded"
? this.collapseGroup($group)
: this.expandGroup($group);
};
FileList.prototype.collapseGroup = function (group) {
var $list = $("> ul, > div.subitems", group),
self = this;
$list.css("overflow", "hidden");
$list.animate(
{ height: 0 },
{
duration: 100,
queue: false,
complete: function () {
$list.css({ overflow: "visible", display: "none" });
$(group).attr("data-status", "collapsed");
$(window).trigger("resize");
},
}
);
this.sendGroupStatusRequest(group, 0);
};
FileList.prototype.expandGroup = function (group) {
var $list = $("> ul, > div.subitems", group),
self = this;
$list.css({ overflow: "hidden", display: "block", height: 0 });
$list.animate(
{ height: $list[0].scrollHeight },
{
duration: 100,
queue: false,
complete: function () {
$list.css({ overflow: "visible", height: "auto" });
$(group).attr("data-status", "expanded");
$(window).trigger("resize");
},
}
);
this.sendGroupStatusRequest(group, 1);
};
FileList.prototype.sendGroupStatusRequest = function (group, status) {
if (this.options.groupStatusHandler !== undefined) {
var groupId = $(group).data("group-id");
if (groupId === undefined) groupId = $("> h4 a", group).text();
$(group).request(this.options.groupStatusHandler, {
data: { group: groupId, status: status },
});
}
};
FileList.prototype.markActive = function (dataId) {
$("li.item", this.$el).removeClass("active");
if (dataId)
$('li.item[data-id="' + dataId + '"]', this.$el).addClass("active");
this.dataId = dataId;
};
FileList.prototype.update = function () {
if (this.dataId !== undefined) this.markActive(this.dataId);
};
var old = $.fn.fileList;
$.fn.fileList = function (option) {
var args = arguments;
return this.each(function () {
var $this = $(this);
var data = $this.data("oc.fileList");
var options = $.extend(
{},
FileList.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data("oc.fileList", (data = new FileList(this, options)));
if (typeof option == "string") {
var methodArgs = [];
for (var i = 1; i < args.length; i++) methodArgs.push(args[i]);
data[option].apply(data, methodArgs);
}
});
};
$.fn.fileList.Constructor = FileList;
$.fn.fileList.noConflict = function () {
$.fn.fileList = old;
return this;
};
$(document).ready(function () {
$("[data-control=filelist]").fileList();
});
})(window.jQuery);
(function ($) {
var OctoberLayout = function () {
this.$accountMenuOverlay = null;
};
OctoberLayout.prototype.setPageTitle = function (title) {
var $title = $("title");
if (this.pageTitleTemplate === undefined)
this.pageTitleTemplate = $title.data("titleTemplate");
$title.text(this.pageTitleTemplate.replace("%s", title));
};
OctoberLayout.prototype.updateLayout = function (title) {
var $children, $el, fixedWidth, margin;
$("[data-calculate-width]").each(function () {
$children = $(this).children();
if ($children.length > 0) {
fixedWidth = 0;
$children.each(function () {
$el = $(this);
margin = $el.data("oc.layoutMargin");
if (margin === undefined) {
margin =
parseInt($el.css("marginRight")) +
parseInt($el.css("marginLeft"));
$el.data("oc.layoutMargin", margin);
}
fixedWidth += $el.get(0).offsetWidth + margin;
});
$(this).width(fixedWidth);
$(this).trigger("oc.widthFixed");
}
});
};
OctoberLayout.prototype.toggleAccountMenu = function (el) {
var self = this,
$el = $(el),
$parent = $(el).parent(),
$menu = $el.next();
$el.tooltip("hide");
if ($menu.hasClass("active")) {
self.$accountMenuOverlay.remove();
$parent.removeClass("highlight");
$menu.removeClass("active");
} else {
self.$accountMenuOverlay = $("<div />").addClass("popover-overlay");
$(document.body).append(self.$accountMenuOverlay);
$parent.addClass("highlight");
$menu.addClass("active");
self.$accountMenuOverlay.one("click", function () {
self.$accountMenuOverlay.remove();
$menu.removeClass("active");
$parent.removeClass("highlight");
});
}
};
if ($.oc === undefined) $.oc = {};
$.oc.layout = new OctoberLayout();
$(document).ready(function () {
$.oc.layout.updateLayout();
window.setTimeout($.oc.layout.updateLayout, 100);
});
$(window).on("resize", function () {
$.oc.layout.updateLayout();
});
$(window).on("oc.updateUi", function () {
$.oc.layout.updateLayout();
});
})(jQuery);
+(function ($) {
"use strict";
var SidePanelTab = function (element, options) {
this.options = options;
this.$el = $(element);
this.init();
};
SidePanelTab.prototype.init = function () {
var self = this;
this.tabOpenDelay = 200;
this.tabOpenTimeout = undefined;
this.panelOpenTimeout = undefined;
this.$sideNav = $("#layout-sidenav");
this.$sideNavItems = $("ul li", this.$sideNav);
this.$sidePanelItems = $("[data-content-id]", this.$el);
this.sideNavWidth = this.$sideNavItems.outerWidth();
this.mainNavHeight = $("#layout-mainmenu").outerHeight();
this.panelVisible = false;
this.visibleItemId = false;
this.$fixButton = $(
'<a href="#" class="fix-button"><i class="icon-thumb-tack"></i></a>'
);
this.$fixButton.click(function () {
self.fixPanel();
return false;
});
$(".fix-button-container", this.$el).append(this.$fixButton);
this.$sideNavItems.click(function () {
if ($(this).data("no-side-panel")) {
return;
}
if (
Modernizr.touchevents &&
$(window).width() < self.options.breakpoint
) {
if (
$(this).data("menu-item") == self.visibleItemId &&
self.panelVisible
) {
self.hideSidePanel();
return;
} else {
self.displaySidePanel();
}
}
self.displayTab(this);
return false;
});
if (!Modernizr.touchevents) {
self.$sideNav.mouseleave(function () {
clearTimeout(self.panelOpenTimeout);
});
self.$el.mouseleave(function () {
self.hideSidePanel();
});
self.$sideNavItems.mouseenter(function () {
if (
$(window).width() < self.options.breakpoint ||
!self.panelFixed()
) {
if ($(this).data("no-side-panel")) {
self.hideSidePanel();
return;
}
var _this = this;
self.tabOpenTimeout = setTimeout(function () {
self.displaySidePanel();
self.displayTab(_this);
}, self.tabOpenDelay);
}
});
self.$sideNavItems.mouseleave(function () {
clearTimeout(self.tabOpenTimeout);
});
$(window).resize(function () {
self.updatePanelPosition();
self.updateActiveTab();
});
} else {
$("#layout-body").click(function () {
if (self.panelVisible) {
self.hideSidePanel();
return false;
}
});
self.$el.on("close.oc.sidePanel", function () {
self.hideSidePanel();
});
}
this.updateActiveTab();
};
SidePanelTab.prototype.displayTab = function (menuItem) {
var menuItemId = $(menuItem).data("menu-item");
this.visibleItemId = menuItemId;
$.oc.sideNav.setActiveItem(menuItemId);
this.$sidePanelItems.each(function () {
var $el = $(this);
$el.toggleClass("hide", $el.data("content-id") != menuItemId);
});
$(window).trigger("resize");
};
SidePanelTab.prototype.displaySidePanel = function () {
$(document.body).addClass("display-side-panel");
this.$el.appendTo("#layout-canvas");
this.panelVisible = true;
this.$el.css({ left: this.sideNavWidth, top: this.mainNavHeight });
this.updatePanelPosition();
$(window).trigger("resize");
};
SidePanelTab.prototype.hideSidePanel = function () {
$(document.body).removeClass("display-side-panel");
if (this.$el.next("#layout-body").length == 0) {
$("#layout-body").before(this.$el);
}
this.panelVisible = false;
this.updateActiveTab();
};
SidePanelTab.prototype.updatePanelPosition = function () {
if (!this.panelFixed() || Modernizr.touchevents) {
this.$el.height($(document).height() - this.mainNavHeight);
} else {
this.$el.css("height", "");
}
if (
this.panelVisible &&
$(window).width() > this.options.breakpoint &&
this.panelFixed()
) {
this.hideSidePanel();
}
};
SidePanelTab.prototype.updateActiveTab = function () {
if (
!this.panelVisible &&
($(window).width() < this.options.breakpoint || !this.panelFixed())
) {
$.oc.sideNav.unsetActiveItem();
} else {
$.oc.sideNav.setActiveItem(this.visibleItemId);
}
};
SidePanelTab.prototype.panelFixed = function () {
return (
!($(window).width() < this.options.breakpoint) &&
!$(document.body).hasClass("side-panel-not-fixed")
);
};
SidePanelTab.prototype.fixPanel = function () {
$(document.body).toggleClass("side-panel-not-fixed");
var self = this;
window.setTimeout(function () {
var fixed = self.panelFixed();
if (fixed) {
self.updateActiveTab();
$(document.body).addClass("side-panel-fix-shadow");
} else {
$(document.body).removeClass("side-panel-fix-shadow");
self.hideSidePanel();
}
if (typeof localStorage !== "undefined")
localStorage.ocSidePanelFixed = fixed ? 1 : 0;
}, 0);
};
SidePanelTab.DEFAULTS = { breakpoint: 769 };
var old = $.fn.sidePanelTab;
$.fn.sidePanelTab = function (option) {
return this.each(function () {
var $this = $(this);
var data = $this.data("oc.sidePanelTab");
var options = $.extend(
{},
SidePanelTab.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data(
"oc.sidePanelTab",
(data = new SidePanelTab(this, options))
);
if (typeof option == "string") data[option].call(data);
});
};
$.fn.sidePanelTab.Constructor = SidePanelTab;
$.fn.sidePanelTab.noConflict = function () {
$.fn.sidePanelTab = old;
return this;
};
$(document).ready(function () {
$("[data-control=layout-sidepanel]").sidePanelTab();
});
$(document).ready(function () {
if (Modernizr.touchevents || typeof localStorage !== "undefined") {
if (localStorage.ocSidePanelFixed == 0) {
$(document.body).addClass("side-panel-not-fixed");
$(window).trigger("resize");
} else if (localStorage.ocSidePanelFixed == 1) {
$(document.body).removeClass("side-panel-not-fixed");
$(window).trigger("resize");
}
}
});
})(window.jQuery);
+(function ($) {
"use strict";
var SimpleList = function (element, options) {
var $el = (this.$el = $(element));
this.options = options || {};
if ($el.hasClass("is-sortable")) {
var sortableOptions = { distance: 10 };
if (this.options.sortableHandle)
sortableOptions[handle] = this.options.sortableHandle;
$el.find("> ul, > ol").sortable(sortableOptions);
}
if ($el.hasClass("is-scrollable")) {
$el.wrapInner($("<div />").addClass("control-scrollbar"));
var $scrollbar = $el.find(">.control-scrollbar:first");
$scrollbar.scrollbar();
}
};
SimpleList.DEFAULTS = { sortableHandle: null };
var old = $.fn.simplelist;
$.fn.simplelist = function (option) {
return this.each(function () {
var $this = $(this);
var data = $this.data("oc.simplelist");
var options = $.extend(
{},
SimpleList.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data(
"oc.simplelist",
(data = new SimpleList(this, options))
);
});
};
$.fn.simplelist.Constructor = SimpleList;
$.fn.simplelist.noConflict = function () {
$.fn.simplelist = old;
return this;
};
$(document).render(function () {
$('[data-control="simplelist"]').simplelist();
});
})(window.jQuery);
+(function ($) {
"use strict";
var Base = $.oc.foundation.base,
BaseProto = Base.prototype;
var TreeListWidget = function (element, options) {
this.$el = $(element);
this.options = options || {};
Base.call(this);
$.oc.foundation.controlUtils.markDisposable(element);
this.init();
};
TreeListWidget.prototype = Object.create(BaseProto);
TreeListWidget.prototype.constructor = TreeListWidget;
TreeListWidget.prototype.init = function () {
var sortableOptions = {
handle: this.options.handle,
nested: this.options.nested,
onDrop: this.proxy(this.onDrop),
afterMove: this.proxy(this.onAfterMove),
};
this.$el.find("> ol").sortable($.extend(sortableOptions, this.options));
if (!this.options.nested)
this.$el
.find("> ol ol")
.sortable($.extend(sortableOptions, this.options));
this.$el.one("dispose-control", this.proxy(this.dispose));
};
TreeListWidget.prototype.dispose = function () {
this.unbind();
BaseProto.dispose.call(this);
};
TreeListWidget.prototype.unbind = function () {
this.$el.off("dispose-control", this.proxy(this.dispose));
this.$el.find("> ol").sortable("destroy");
if (!this.options.nested) {
this.$el.find("> ol ol").sortable("destroy");
}
this.$el.removeData("oc.treelist");
this.$el = null;
this.options = null;
};
TreeListWidget.DEFAULTS = { handle: null, nested: true };
TreeListWidget.prototype.onDrop = function ($item, container, _super) {
if (!this.$el) {
return;
}
this.$el.trigger("move.oc.treelist", {
item: $item,
container: container,
});
_super($item, container);
};
TreeListWidget.prototype.onAfterMove = function (
$placeholder,
container,
$closestEl
) {
if (!this.$el) {
return;
}
this.$el.trigger("aftermove.oc.treelist", {
placeholder: $placeholder,
container: container,
closestEl: $closestEl,
});
};
var old = $.fn.treeListWidget;
$.fn.treeListWidget = function (option) {
var args = arguments,
result;
this.each(function () {
var $this = $(this);
var data = $this.data("oc.treelist");
var options = $.extend(
{},
TreeListWidget.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data(
"oc.treelist",
(data = new TreeListWidget(this, options))
);
if (typeof option == "string") result = data[option].call(data);
if (typeof result != "undefined") return false;
});
return result ? result : this;
};
$.fn.treeListWidget.Constructor = TreeListWidget;
$.fn.treeListWidget.noConflict = function () {
$.fn.treeListWidget = old;
return this;
};
$(document).render(function () {
$('[data-control="treelist"]').treeListWidget();
});
})(window.jQuery);
+(function ($) {
"use strict";
var SidenavTree = function (element, options) {
this.options = options;
this.$el = $(element);
this.init();
};
SidenavTree.DEFAULTS = { treeName: "sidenav_tree" };
SidenavTree.prototype.init = function () {
var self = this;
$(document.body).addClass("has-sidenav-tree");
this.statusCookieName = this.options.treeName + "groupStatus";
this.searchCookieName = this.options.treeName + "search";
this.$searchInput = $(this.options.searchInput);
this.$el.on("click", "li > div.group", function () {
self.toggleGroup($(this).closest("li"));
return false;
});
this.$searchInput.on("input", function () {
self.handleSearchChange();
});
var searchTerm = $.cookie(this.searchCookieName);
if (searchTerm !== undefined && searchTerm.length > 0) {
this.$searchInput.val(searchTerm);
this.applySearch();
}
var scrollbar = $("[data-control=scrollbar]", this.$el).data(
"oc.scrollbar"
),
active = $("li.active", this.$el);
if (active.length > 0) {
scrollbar.gotoElement(active);
}
};
SidenavTree.prototype.toggleGroup = function (group) {
var $group = $(group),
status = $group.attr("data-status");
status === undefined || status == "expanded"
? this.collapseGroup($group)
: this.expandGroup($group);
};
SidenavTree.prototype.collapseGroup = function (group) {
var $list = $("> ul", group),
self = this;
$list.css("overflow", "hidden");
$list.animate(
{ height: 0 },
{
duration: 100,
queue: false,
complete: function () {
$list.css({ overflow: "visible", display: "none" });
$(group).attr("data-status", "collapsed");
$(window).trigger("oc.updateUi");
self.saveGroupStatus($(group).data("group-code"), true);
},
}
);
};
SidenavTree.prototype.expandGroup = function (group, duration) {
var $list = $("> ul", group),
self = this;
duration = duration === undefined ? 100 : duration;
$list.css({ overflow: "hidden", height: 0 });
$list.animate(
{ height: $list[0].scrollHeight },
{
duration: duration,
queue: false,
complete: function () {
$list.css({
overflow: "visible",
height: "auto",
display: "",
});
$(group).attr("data-status", "expanded");
$(window).trigger("oc.updateUi");
self.saveGroupStatus($(group).data("group-code"), false);
},
}
);
};
SidenavTree.prototype.saveGroupStatus = function (groupCode, collapsed) {
var collapsedGroups = $.cookie(this.statusCookieName),
updatedGroups = [];
if (collapsedGroups === undefined) {
collapsedGroups = "";
}
collapsedGroups = collapsedGroups.split("|");
$.each(collapsedGroups, function () {
if (groupCode != this) updatedGroups.push(this);
});
if (collapsed) {
updatedGroups.push(groupCode);
}
$.cookie(this.statusCookieName, updatedGroups.join("|"), {
expires: 30,
path: "/",
});
};
SidenavTree.prototype.handleSearchChange = function () {
var lastValue = this.$searchInput.data("oc.lastvalue");
if (lastValue !== undefined && lastValue == this.$searchInput.val()) {
return;
}
this.$searchInput.data("oc.lastvalue", this.$searchInput.val());
if (this.dataTrackInputTimer !== undefined) {
window.clearTimeout(this.dataTrackInputTimer);
}
var self = this;
this.dataTrackInputTimer = window.setTimeout(function () {
self.applySearch();
}, 300);
$.cookie(this.searchCookieName, $.trim(this.$searchInput.val()), {
expires: 30,
path: "/",
});
};
SidenavTree.prototype.applySearch = function () {
var query = $.trim(this.$searchInput.val()),
words = query.toLowerCase().split(" "),
visibleGroups = [],
visibleItems = [],
self = this;
if (query.length == 0) {
$("li", this.$el).removeClass("hidden");
return;
}
$("ul.top-level > li", this.$el).each(function () {
var $li = $(this);
if (self.textContainsWords($("div.group h3", $li).text(), words)) {
visibleGroups.push($li.get(0));
$("ul li", $li).each(function () {
visibleItems.push(this);
});
} else {
$("ul li", $li).each(function () {
if (
self.textContainsWords($(this).text(), words) ||
self.textContainsWords($(this).data("keywords"), words)
) {
visibleGroups.push($li.get(0));
visibleItems.push(this);
}
});
}
});
$("ul.top-level > li", this.$el).each(function () {
var $li = $(this),
groupIsVisible = $.inArray(this, visibleGroups) !== -1;
$li.toggleClass("hidden", !groupIsVisible);
if (groupIsVisible) self.expandGroup($li, 0);
$("ul li", $li).each(function () {
var $itemLi = $(this);
$itemLi.toggleClass(
"hidden",
$.inArray(this, visibleItems) == -1
);
});
});
return false;
};
SidenavTree.prototype.textContainsWords = function (text, words) {
text = text.toLowerCase();
for (var i = 0; i < words.length; i++) {
if (text.indexOf(words[i]) === -1) return false;
}
return true;
};
var old = $.fn.sidenavTree;
$.fn.sidenavTree = function (option) {
var args = arguments;
return this.each(function () {
var $this = $(this);
var data = $this.data("oc.sidenavTree");
var options = $.extend(
{},
SidenavTree.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data(
"oc.sidenavTree",
(data = new SidenavTree(this, options))
);
if (typeof option == "string") {
var methodArgs = [];
for (var i = 1; i < args.length; i++) methodArgs.push(args[i]);
data[option].apply(data, methodArgs);
}
});
};
$.fn.sidenavTree.Constructor = SidenavTree;
$.fn.sidenavTree.noConflict = function () {
$.fn.sidenavTree = old;
return this;
};
$(document).ready(function () {
$("[data-control=sidenav-tree]").sidenavTree();
});
})(window.jQuery);
+(function ($) {
"use strict";
var Base = $.oc.foundation.base,
BaseProto = Base.prototype;
var DateTimeConverter = function (element, options) {
this.$el = $(element);
this.options = options || {};
$.oc.foundation.controlUtils.markDisposable(element);
Base.call(this);
this.init();
};
DateTimeConverter.prototype = Object.create(BaseProto);
DateTimeConverter.prototype.constructor = DateTimeConverter;
DateTimeConverter.prototype.init = function () {
this.initDefaults();
this.$el.text(this.getDateTimeValue());
this.$el.one("dispose-control", this.proxy(this.dispose));
};
DateTimeConverter.prototype.initDefaults = function () {
if (!this.options.timezone) {
this.options.timezone = $('meta[name="backend-timezone"]').attr(
"content"
);
}
if (!this.options.locale) {
this.options.locale = $('meta[name="backend-locale"]').attr(
"content"
);
}
if (!this.options.format) {
this.options.format = "llll";
}
if (this.options.formatAlias) {
this.options.format = this.getFormatFromAlias(
this.options.formatAlias
);
}
this.appTimezone = $('meta[name="app-timezone"]').attr("content");
if (!this.appTimezone) {
this.appTimezone = "UTC";
}
};
DateTimeConverter.prototype.getDateTimeValue = function () {
this.datetime = this.$el.attr("datetime");
if (this.$el.get(0).hasAttribute("data-ignore-timezone")) {
this.appTimezone = "UTC";
this.options.timezone = "UTC";
}
var momentObj = moment.tz(this.datetime, this.appTimezone),
result;
if (this.options.locale) {
momentObj = momentObj.locale(this.options.locale);
}
if (this.options.timezone) {
momentObj = momentObj.tz(this.options.timezone);
}
if (this.options.timeSince) {
result = momentObj.fromNow();
} else if (this.options.timeTense) {
result = momentObj.calendar();
} else {
result = momentObj.format(this.options.format);
}
return result;
};
DateTimeConverter.prototype.getFormatFromAlias = function (alias) {
var map = {
time: "LT",
timeLong: "LTS",
date: "L",
dateMin: "l",
dateLong: "LL",
dateLongMin: "ll",
dateTime: "LLL",
dateTimeMin: "lll",
dateTimeLong: "LLLL",
dateTimeLongMin: "llll",
};
return map[alias] ? map[alias] : "llll";
};
DateTimeConverter.prototype.dispose = function () {
this.$el.off("dispose-control", this.proxy(this.dispose));
this.$el.removeData("oc.dateTimeConverter");
this.$el = null;
this.options = null;
BaseProto.dispose.call(this);
};
DateTimeConverter.DEFAULTS = {
format: null,
formatAlias: null,
timezone: null,
locale: null,
timeTense: false,
timeSince: false,
};
var old = $.fn.dateTimeConverter;
$.fn.dateTimeConverter = function (option) {
var args = Array.prototype.slice.call(arguments, 1),
items,
result;
items = this.each(function () {
var $this = $(this);
var data = $this.data("oc.dateTimeConverter");
var options = $.extend(
{},
DateTimeConverter.DEFAULTS,
$this.data(),
typeof option == "object" && option
);
if (!data)
$this.data(
"oc.dateTimeConverter",
(data = new DateTimeConverter(this, options))
);
if (typeof option == "string")
result = data[option].apply(data, args);
if (typeof result != "undefined") return false;
});
return result ? result : items;
};
$.fn.dateTimeConverter.Constructor = DateTimeConverter;
$.fn.dateTimeConverter.noConflict = function () {
$.fn.dateTimeConverter = old;
return this;
};
$(document).render(function () {
$("time[data-datetime-control]").dateTimeConverter();
});
})(window.jQuery);
$.ajaxPrefilter(function (options) {
var token = $('meta[name="csrf-token"]').attr("content");
if (token) {
if (!options.headers) options.headers = {};
options.headers["X-CSRF-TOKEN"] = token;
}
});
if ($.oc === undefined) $.oc = {};
$.oc.backendUrl = function (url) {
var backendBasePath = $('meta[name="backend-base-path"]').attr("content");
if (!backendBasePath) return url;
if (url.substr(0, 1) == "/") url = url.substr(1);
return backendBasePath + "/" + url;
};
AssetManager = function () {
var o = {
load: function (collection, callback) {
var jsList = collection.js ? collection.js : [],
cssList = collection.css ? collection.css : [],
imgList = collection.img ? collection.img : [];
jsList = $.grep(jsList, function (item) {
return $('head script[src="' + item + '"]').length == 0;
});
cssList = $.grep(cssList, function (item) {
return $('head link[href="' + item + '"]').length == 0;
});
var cssCounter = 0,
jsLoaded = false,
imgLoaded = false;
if (
jsList.length === 0 &&
cssList.length === 0 &&
imgList.length === 0
) {
callback && callback();
return;
}
o.loadJavaScript(jsList, function () {
jsLoaded = true;
checkLoaded();
});
$.each(cssList, function (index, source) {
o.loadStyleSheet(source, function () {
cssCounter++;
checkLoaded();
});
});
o.loadImage(imgList, function () {
imgLoaded = true;
checkLoaded();
});
function checkLoaded() {
if (!imgLoaded) return false;
if (!jsLoaded) return false;
if (cssCounter < cssList.length) return false;
callback && callback();
}
},
loadStyleSheet: function (source, callback) {
var cssElement = document.createElement("link");
cssElement.setAttribute("rel", "stylesheet");
cssElement.setAttribute("type", "text/css");
cssElement.setAttribute("href", source);
cssElement.addEventListener("load", callback, false);
if (typeof cssElement != "undefined") {
document
.getElementsByTagName("head")[0]
.appendChild(cssElement);
}
return cssElement;
},
loadJavaScript: function (sources, callback) {
if (sources.length <= 0) return callback();
var source = sources.shift(),
jsElement = document.createElement("script");
jsElement.setAttribute("type", "text/javascript");
jsElement.setAttribute("src", source);
jsElement.addEventListener(
"load",
function () {
o.loadJavaScript(sources, callback);
},
false
);
if (typeof jsElement != "undefined") {
document.getElementsByTagName("head")[0].appendChild(jsElement);
}
},
loadImage: function (sources, callback) {
if (sources.length <= 0) return callback();
var loaded = 0;
$.each(sources, function (index, source) {
var img = new Image();
img.onload = function () {
if (++loaded == sources.length && callback) callback();
};
img.src = source;
});
},
};
return o;
};
assetManager = new AssetManager();
if ($.oc === undefined) $.oc = {};
$.oc.escapeHtmlString = function (string) {
var htmlEscapes = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
},
htmlEscaper = /[&<>"'\/]/g;
return ("" + string).replace(htmlEscaper, function (match) {
return htmlEscapes[match];
});
};
if (!!window.MSInputMethodContext && !!document.documentMode) {
$(window).on("resize", function () {
fixMediaManager();
fixSidebar();
});
function fixMediaManager() {
var $el = $('div[data-control="media-manager"] .control-scrollpad');
$el.height($el.parent().height());
}
function fixSidebar() {
$("#layout-sidenav").height(
Math.max(
$("#layout-body").innerHeight(),
$(window).height() - $("#layout-mainmenu").height()
)
);
}
}
|
/*
* GET home page.
*/
exports.show = function(req, res){
//res.redirect('editor');
res.render('editor', { title: 'CMPE 272',user:req.user });
}; |
import React from 'react';
export default function Schedule({ day }) {
if ( day === 'workshop' ) {
return (
<table>
<thead>
<tr>
<th>Time</th>
<th>Event</th>
<th>Instructor</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td><time>8:30am</time></td>
<td>Arrivals, set up</td>
<td></td>
<td>3rd Floor</td>
</tr>
<tr>
<td><time>9:00am</time></td>
<td>Get in the Fast Lane: Measuring Web Performance</td>
<td>Sia Karamalegos</td>
<td>3rd Floor - Room 214A</td>
</tr>
<tr>
<td><time>9:00am</time></td>
<td>Zero Dependency Components: Introduction to Web Components</td>
<td>Nate Clark</td>
<td>3rd Floor - Room 213</td>
</tr>
</tbody>
</table>
)
}
return (
<table>
<thead>
<tr>
<th>Time</th>
<th>Event</th>
<th>Speaker</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td><time>7:30am - 10:00am</time></td>
<td>Registration</td>
<td></td>
<td>3rd Floor Corridor</td>
</tr>
<tr>
<td><time>9:00am</time></td>
<td>Empower Through Web Development</td>
<td>Blake Watson</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>9:30am</time></td>
<td>Master the JavaScript Interview</td>
<td>Tyler Clark</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>9:55am</time></td>
<td>Renderless Components with Hooks</td>
<td>Ken Wheeler</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>10:25am</time></td>
<td>Break</td>
<td></td>
<td></td>
</tr>
<tr>
<td><time>10:35am</time></td>
<td>The Future of Front-End Performance</td>
<td>Sia Karamalegos</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>11:05am</time></td>
<td>The WebAssembly Revolution Has Begun</td>
<td>Jay Phelps</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>11:35am</time></td>
<td>Using JS to Bridge the Tech and Culture Gap</td>
<td>Michael Liendo</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>12:00pm</time></td>
<td>Transition to Lunch</td>
<td></td>
<td></td>
</tr>
<tr>
<td><time>12:00pm - 1:40pm</time></td>
<td>Lunch</td>
<td></td>
<td>Rooms 301-304</td>
</tr>
<tr>
<td><time>12:20pm</time></td>
<td>Overview: Mississippi Coding Academies</td>
<td>Bryce Mullican</td>
<td>Lunch Stage - Rooms 301-304</td>
</tr>
<tr>
<td><time>12:30pm</time></td>
<td>Join the Revolution</td>
<td>Gant Laborde</td>
<td>Lunch Stage - Rooms 301-304</td>
</tr>
<tr>
<td><time>1:30pm</time></td>
<td>Break</td>
<td></td>
<td></td>
</tr>
<tr>
<td><time>1:40pm</time></td>
<td>JavaScript: who, what, where, why and next</td>
<td>Laurie Voss</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>2:10pm</time></td>
<td>Dissecting the fluff from the buff of TDD, Twitter Driven Development</td>
<td>Justin Samuels</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>2:35pm</time></td>
<td>How to Avoid SUX (Some User Experience)</td>
<td>Kayla Sween</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>3:00pm</time></td>
<td>Break</td>
<td></td>
<td></td>
</tr>
<tr>
<td><time>3:10pm</time></td>
<td>Full Stack Development in the Era of Serverless Computing</td>
<td>Nader Dabit</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>3:40pm</time></td>
<td>The Future of JavaScript Apps is Gatsby.js</td>
<td>Joe Previte</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>4:10pm</time></td>
<td>Break</td>
<td></td>
<td></td>
</tr>
<tr>
<td><time>4:20pm</time></td>
<td>Buliding the Next Generation of Mobile Apps Using Draftbit</td>
<td>Peter Piekarczyk</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>4:45pm</time></td>
<td>So Many Hats: Security for Web Developers</td>
<td>Vince Falconi</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>5:10pm</time></td>
<td>Writing Code Saved My Life</td>
<td>Kurt Kemple</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>5:40pm</time></td>
<td>Door Prizes / Announcements / Dismissal</td>
<td>J.C. Hiatt / Kenneth LaFrance</td>
<td>Main Stage - Theater</td>
</tr>
<tr>
<td><time>8:30pm</time></td>
<td>After Party - Open Invite!</td>
<td></td>
<td><a href="https://www.google.com/maps/place/Fondren+Public/@32.3335561,-90.1775031,17z/data=!3m1!4b1!4m5!3m4!1s0x862832e9d6869733:0xc8ea3c87956e4dda!8m2!3d32.3335516!4d-90.1753144">Fondren Public</a></td>
</tr>
</tbody>
</table>
)
} |
# flake8: noqa
from tdp_core.dbview import DBConnector, DBMapping
from .pg_agg_score import agg_score
from .entity import cellline, gene, tissue, drug
from .data import cellline_data, tissue_data, cellline_depletion, cellline_drug, cellline_drug_screen
from .query_common import create_common
from .query_gene import create_gene
from .query_sample import create_sample
from .query_score import create_gene_sample_score
from tdp_core.dbview import DBViewBuilder, inject_where, limit_offset
from .query_drug import create_drug, create_drug_sample_score, create_drug_screen_sample
__author__ = 'Samuel Gratzl'
views = dict()
# gene
create_common(views, gene)
create_gene(views, gene)
# cellline
create_common(views, cellline)
create_sample(views, cellline, gene, cellline_data)
# drug
create_drug(views, drug)
create_drug_screen_sample(views,cellline, cellline_drug_screen)
create_drug_sample_score(views, cellline, drug, cellline_drug, 'drug_')
# scores cellline x gene
create_gene_sample_score(views, gene, cellline, cellline_data)
create_gene_sample_score(views, cellline, gene, cellline_data, inline_aggregate_sample_filter=True)
# tissue
create_common(views, tissue)
create_sample(views, tissue, gene, tissue_data)
# scores tissue x gene
create_gene_sample_score(views, gene, tissue, tissue_data)
create_gene_sample_score(views, tissue, gene, tissue_data, inline_aggregate_sample_filter=True)
# depletion scores
create_gene_sample_score(views, gene, cellline, cellline_depletion, 'depletion_', callback=lambda x: x.filter('depletionscreen'))
create_gene_sample_score(views, cellline, gene, cellline_depletion, 'depletion_', inline_aggregate_sample_filter=True, callback=lambda x: x.filter('depletionscreen'))
# idtype mappings
mappings = [
DBMapping(cellline.idtype, 'Cosmic',
"""SELECT {s.id} as f, CAST(cosmicid as text) as t
FROM {s.table}
WHERE {s.id} = ANY(:ids) AND cosmicid is NOT NULL""".format(s=cellline)),
DBMapping('Cosmic', cellline.idtype,
"""SELECT CAST(cosmicid as text) as t, {s.id} as t
FROM {s.table}
WHERE cosmicid = ANY(:ids)""".format(s=cellline), integer_ids=True),
DBMapping(gene.idtype, 'GeneSymbol',
"""SELECT {g.id} AS f, symbol as t
FROM {g.table} WHERE {g.id} = ANY(:ids)""".format(g=gene)),
DBMapping('GeneSymbol', gene.idtype,
"""SELECT symbol as f, {g.id} AS t
FROM {g.table} WHERE symbol = ANY(:ids)""".format(g=gene))
]
def create():
d = DBConnector(views, agg_score, mappings=mappings)
d.description = 'TCGA/CCLE database as assembled by Boehringer Ingelheim GmbH'
return d
|
"""
eZmax API Definition (Full)
This API expose all the functionnalities for the eZmax and eZsign applications. # noqa: E501
The version of the OpenAPI document: 1.1.7
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import eZmaxApi
from eZmaxApi.model.common_response import CommonResponse
from eZmaxApi.model.common_response_obj_debug import CommonResponseObjDebug
from eZmaxApi.model.common_response_obj_debug_payload import CommonResponseObjDebugPayload
globals()['CommonResponse'] = CommonResponse
globals()['CommonResponseObjDebug'] = CommonResponseObjDebug
globals()['CommonResponseObjDebugPayload'] = CommonResponseObjDebugPayload
from eZmaxApi.model.ezsigntemplate_edit_object_v1_response import EzsigntemplateEditObjectV1Response
class TestEzsigntemplateEditObjectV1Response(unittest.TestCase):
"""EzsigntemplateEditObjectV1Response unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testEzsigntemplateEditObjectV1Response(self):
"""Test EzsigntemplateEditObjectV1Response"""
# FIXME: construct object with mandatory attributes with example values
# model = EzsigntemplateEditObjectV1Response() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
# -*- coding:utf8 -*-
# File : __init__.py
# Author : Jiayuan Mao
# Email : [email protected]
# Date : 12/29/16
#
# This file is part of TensorArtist.
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S10.1.8_A1;
* @section: 10.1.8;
* @assertion: When control enters an execution context for function code,
* an arguments object is created and initialised;
* @description: Executing function which uses arguments object;
*/
//CHECK#1
function f1(){
return arguments;
}
try{
var x = f1();
}
catch(e){
$ERROR("#1: arguments doesn't exists");
}
//CHECK#2
var f2 = function(){
return arguments;
}
try{
var x = f2();
}
catch(e){
$ERROR("#2: arguments doesn't exists");
}
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import sortBy from 'sort-by'
import Book from './Book'
import * as BooksAPI from './BooksAPI'
class SearchBooks extends Component {
static propTypes = {
onUpdateBook: PropTypes.func.isRequired,
books: PropTypes.array.isRequired
}
state = {
query: '',
searchBooks: []
}
// Updates query and searches with BooksAPI, then assigns returned data to searchBooks array.
onUpdateQuery = (query) => {
this.setState({ query: query.trim() }, () => {
BooksAPI.search(this.state.query, 20).then(data => {
this.setState({ searchBooks: data })
})
})
}
render() {
// Checks if search returned any books and if it does sorts books by title
// and assigns data to Book component for each book
if(this.state.searchBooks) {
if(!this.state.searchBooks.error){
this.state.searchBooks.sort(sortBy('title'))
var eachBook = this.state.searchBooks.map((book) => {
return <li key={book.id}><Book
books={this.props.books}
onUpdateBook={this.props.onUpdateBook}
book={book} />
</li>
})
}
}
return (
<div className="search-books">
<div className="search-books-bar">
<Link className="close-search" to='/'>Close</Link>
<div className="search-books-input-wrapper">
<input type="text"
placeholder="Search by title or author"
value={this.state.query}
onChange={(event) => this.onUpdateQuery(event.target.value)}
/>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
{eachBook}
</ol>
</div>
</div>
)
}
}
export default SearchBooks
|
define([], () => {
class AsyncQueue {
constructor(config) {
this.queue = [];
this.queuePauseTime = (config && config.queuePauseTime) || 0;
this.itemId = 0;
this.timer = null;
}
processQueue() {
const item = this.queue.shift();
if (item) {
try {
item.onRun();
} catch (ex) {
if (item.onError) {
try {
item.onError(ex);
} catch (ignore) {
console.error('ERROR running onerror');
console.error(ex);
}
} else {
console.error('Error processing queue item');
console.error(ex);
}
} finally {
this.start();
}
}
}
start() {
this.timer = window.setTimeout(() => {
this.processQueue();
}, this.queuePauseTime);
}
stop() {
window.clearTimeout(this.timer);
this.timer = null;
}
addItem(item) {
this.itemId += 1;
item.id = this.itemId;
this.queue.push(item);
this.start();
}
}
return AsyncQueue;
});
|
import React, { useState, useEffect, useMemo } from 'react'
import { Link, graphql } from 'gatsby'
import Helmet from 'react-helmet'
import Layout from '../components/Layout'
import Posts from '../components/Posts'
import Guides from '../components/Guides'
import Projects from '../components/Projects'
import SEO from '../components/SEO'
import Blurb from '../components/Blurb'
import { getSimplifiedPosts } from '../utils/helpers'
import config from '../utils/config'
import projects from '../data/projects'
import interviews from '../data/interviews'
import speaking from '../data/speaking'
export default function BlogIndex({ data }) {
const [followers, setFollowers] = useState(0)
const latest = data.latest.edges
const popular = data.popular.edges
const simplifiedLatest = useMemo(() => getSimplifiedPosts(latest), [latest])
const simplifiedPopular = useMemo(() => getSimplifiedPosts(popular), [
popular,
])
useEffect(() => {
async function getGithubAPI() {
// If you fork this and don't change this, I will find you
const response = await fetch('https://api.github.com/users/tkssharma')
const data = await response.json()
return data
}
getGithubAPI().then((data) => {
setFollowers(data.followers)
})
}, [])
const Section = ({ title, children, button, ...props }) => (
<section {...props}>
<h2 className="section-title">
{title}
{button && (
<Link className="section-button" to="/blog">
View all
</Link>
)}
</h2>
{children}
</section>
)
return (
<Layout>
<Helmet title={config.siteTitle} />
<SEO />
<Blurb title="I'm Tarun.">
<p>
I'm a software engineer and writer. This website is my digital garden
— a compendium of the things I've learned and created over the
years.
</p>
{followers && (
<p>
<a
className="button github-button"
href="https://github.com/tkssharma"
target="_blank"
rel="noopener noreferrer"
style={{ display: 'inline-flex' }}
>
<svg
viewBox="0 0 16 16"
width="20"
height="20"
aria-hidden="true"
style={{ marginRight: '0.75rem' }}
>
<path
fill="white"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"
></path>
</svg>
{`${followers.toLocaleString()} following`}
</a>
</p>
)}
</Blurb>
<div className="container index">
<Section title="Latest Articles." button>
<Posts data={simplifiedLatest} />
</Section>
<Section title="Popular Articles." button>
<Posts data={simplifiedPopular} />
</Section>
<Section title="Projects.">
<Projects data={projects} />
</Section>
<Section title="Interviews.">
<Guides data={interviews} frontPage />
</Section>
<Section title="Speaking.">
<Guides data={speaking} frontPage />
</Section>
<Section title="Newsletter.">
<div className="flex justify-between">
<p className="paragraph">
I send out an email when I create something new.
</p>
<a
href="https://tkssharma.substack.com/subscribe"
target="_blank"
rel="noreferrer"
className="button"
style={{ textAlign: 'center', marginLeft: '.5rem' }}
>
Get the newsletter
</a>
</div>
</Section>
</div>
</Layout>
)
}
export const pageQuery = graphql`
query IndexQuery {
latest: allMarkdownRemark(
limit: 5
sort: { fields: [frontmatter___date], order: DESC }
filter: { frontmatter: { template: { eq: "post" } } }
) {
edges {
node {
id
fields {
slug
}
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
tags
}
}
}
}
popular: allMarkdownRemark(
limit: 20
sort: { fields: [frontmatter___date], order: DESC }
filter: { frontmatter: { categories: { eq: "Popular" } } }
) {
edges {
node {
id
fields {
slug
}
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
tags
}
}
}
}
}
`
|
body.html('');
body.append('button')
.html('English')
.on('click', function () {
d3.text(src, load);
});
body.append('button')
.html('中文')
.on('click', function () {
d3.text(src_chinese, load);
});
ol = body.append('ol');
src = 'https://bigdata-mindstorms.github.io/d3-playground/ontouchstart/2016/01/02/data.yaml';
src_chinese = 'https://bigdata-mindstorms.github.io/d3-playground/ontouchstart/2016/01/02/data_chinese.yaml';
function update(d) {
selection = ol.selectAll('li').data(d);
selection.enter().append('li');
selection.exit().remove();
selection.html(function (item) {
return item.name;
})
.style('color', function (item) {
return item.color;
})
.style('background-color', function (item) {
return item['background-color'];
});
}
function load(e, d) {
if(!e) {
update(js_yaml.load(d));
}
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Simon Dodsley ([email protected])
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: purefa_pg
version_added: '2.4'
short_description: Manage protection groups on Pure Storage FlashArrays
description:
- Create, delete or modify protection groups on Pure Storage FlashArrays.
author:
- Simon Dodsley (@sdodsley)
options:
pgroup:
description:
- The name of the protection group.
required: true
state:
description:
- Define whether the protection group should exist or not.
default: present
choices: [ absent, present ]
volume:
description:
- List of existing volumes to add to protection group.
host:
description:
- List of existing hosts to add to protection group.
hostgroup:
description:
- List of existing hostgroups to add to protection group.
eradicate:
description:
- Define whether to eradicate the protection group on delete and leave in trash.
type : bool
default: 'no'
enabled:
description:
- Define whether to enabled snapshots for the protection group.
type : bool
default: 'yes'
extends_documentation_fragment:
- purestorage.fa
'''
EXAMPLES = r'''
- name: Create new protection group
purefa_pg:
pgroup: foo
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
- name: Create new protection group with snapshots disabled
purefa_pg:
pgroup: foo
enabled: false
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
- name: Delete protection group
purefa_pg:
pgroup: foo
eradicate: true
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
state: absent
- name: Create protection group for hostgroups
purefa_pg:
pgroup: bar
hostgroup:
- hg1
- hg2
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
- name: Create protection group for hosts
purefa_pg:
pgroup: bar
host:
- host1
- host2
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
- name: Create protection group for volumes
purefa_pg:
pgroup: bar
volume:
- vol1
- vol2
fa_url: 10.10.10.2
api_token: e31060a7-21fc-e277-6240-25983c6c4592
'''
RETURN = r'''
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pure import get_system, purefa_argument_spec
try:
from purestorage import purestorage
HAS_PURESTORAGE = True
except ImportError:
HAS_PURESTORAGE = False
def get_pgroup(module, array):
pgroup = None
for h in array.list_pgroups():
if h["name"] == module.params['pgroup']:
pgroup = h
break
return pgroup
def make_pgroup(module, array):
changed = True
if not module.check_mode:
host = array.create_pgroup(module.params['pgroup'])
array.set_pgroup(module.params['pgroup'], snap_enabled=module.params['enabled'])
if module.params['volume']:
array.set_pgroup(module.params['pgroup'], vollist=module.params['volume'])
if module.params['host']:
array.set_pgroup(module.params['pgroup'], hostlist=module.params['host'])
if module.params['hostgroup']:
array.set_pgroup(module.params['pgroup'], hgrouplist=module.params['hostgroup'])
module.exit_json(changed=changed)
def update_pgroup(module, array):
changed = False
pgroup = module.params['pgroup']
module.exit_json(changed=changed)
def delete_pgroup(module, array):
changed = True
if not module.check_mode:
array.destroy_pgroup(module.params['pgroup'])
if module.params['eradicate']:
array.eradicate_pgroup(module.params['pgroup'])
module.exit_json(changed=changed)
def main():
argument_spec = purefa_argument_spec()
argument_spec.update(dict(
pgroup=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['absent', 'present']),
volume=dict(type='list'),
host=dict(type='list'),
hostgroup=dict(type='list'),
eradicate=dict(type='bool', default=False),
enabled=dict(type='bool', default=True),
))
module = AnsibleModule(argument_spec, supports_check_mode=True)
if not HAS_PURESTORAGE:
module.fail_json(msg='purestorage sdk is required for this module in host')
state = module.params['state']
array = get_system(module)
pgroup = get_pgroup(module, array)
if module.params['host']:
try:
for h in module.params['host']:
array.get_host(h)
except:
module.fail_json(msg='Host {} not found'.format(h))
if module.params['hostgroup']:
try:
for hg in module.params['hostgroup']:
array.get_hgroup(hg)
except:
module.fail_json(msg='Hostgroup {} not found'.format(hg))
if pgroup and state == 'present':
update_pgroup(module, array)
elif pgroup and state == 'absent':
delete_pgroup(module, array)
elif pgroup is None and state == 'absent':
module.exit_json(changed=False)
else:
make_pgroup(module, array)
if __name__ == '__main__':
main()
|
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.5
Version: 1.8.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v1.8/admin/
*/
var handleDataTableColVis = function() {
"use strict";
if ($('#data-table').length !== 0) {
$('#data-table').DataTable({
dom: 'C<"clear">lfrtip'
});
}
};
var TableManageColVis = function () {
"use strict";
return {
//main function
init: function () {
handleDataTableColVis();
}
};
}(); |
exports.info = {
'number': 115,
'species': '**Kangaskhan** (**ガルーラ** *Garura*)',
'types' : 'Normal',
'pokedexEntry': 'Kangaskhan protects its child by keeping it in its pouch. It has zero forgiveness for those who harm its child and will beat them down. You shouldn\'t get close to the child when it\'s playing outside its mother\'s pouch. Its mother is always nearby watching over it.\n\n*Dex entry from USUM*',
'genderRatio': { M: 0.000, F: 1.000 },
'catchRate': { integer: 45, percentage: '11.9%' },
'baseStats': { hp: 105, atk: 95, def: 80, spAtk: 40, spDef: 80, spd: 90 },
'abilities': { 0: 'Early Bird *or* Scrappy', 'M': 'Parental Bond', 'H': 'Inner Focus' },
'height': 2.2,
'weight': 176.4,
'colorHex': '#BA9375',
'colorHexShiny': '#B3A9A3',
'color': 'Slightly Desaturated Orange',
'colorShiny': 'Grayish Orange',
'evolvesTo': { species: 'Mega Kangaskhan', level: null, triggeredBy: 'Mega Evolution with Kangaskhanite' },
'eggGroups': ['Monster'],
'hatchTime': '5140 - 5396 steps',
'gif': 'https://play.pokemonshowdown.com/sprites/xyani/kangaskhan.gif',
'gifShiny': 'https://play.pokemonshowdown.com/sprites/xyani-shiny/kangaskhan.gif',
'legendary': false,
'mythical': false
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Constants_1 = require("./Constants");
var Enums_1 = require("./Enums");
var RequestSender_1 = require("./RequestSender");
var SIPMessage_1 = require("./SIPMessage");
/*
* @augments SIP
* @class Class creating a SIP dialog. RFC 3261 12.1
* @param {SIP.RTCSession} owner
* @param {SIP.IncomingRequest|SIP.IncomingResponse} message
* @param {Enum} type UAC / UAS
* @param {Enum} state SIP.Dialog.C.STATUS_EARLY / SIP.Dialog.C.STATUS_CONFIRMED
*/
var Dialog = /** @class */ (function () {
function Dialog(owner, message, type, state) {
this.pracked = [];
this.uacPendingReply = false;
this.uasPendingReply = false;
this.type = Enums_1.TypeStrings.Dialog;
if (!message.hasHeader("contact")) {
throw new Error("unable to create a Dialog without Contact header field");
}
if (message.type === Enums_1.TypeStrings.IncomingResponse) {
var statusCode = message.statusCode;
state = (statusCode && statusCode < 200) ?
Enums_1.DialogStatus.STATUS_EARLY : Enums_1.DialogStatus.STATUS_CONFIRMED;
}
else {
// Create confirmed dialog if state is not defined
state = state || Enums_1.DialogStatus.STATUS_CONFIRMED;
}
var contact = message.parseHeader("contact");
// RFC 3261 12.1.1
if (type === "UAS" && message.type === Enums_1.TypeStrings.IncomingRequest) {
this.id = {
callId: message.callId,
localTag: message.toTag,
remoteTag: message.fromTag,
toString: function () {
return message.callId + message.toTag + message.fromTag;
}
};
this.state = state;
this.remoteSeqnum = message.cseq;
this.localUri = (message.parseHeader("to") || {}).uri;
this.remoteUri = (message.parseHeader("from") || {}).uri;
this.remoteTarget = contact.uri;
this.routeSet = message.getHeaders("record-route");
this.inviteSeqnum = message.cseq;
this.localSeqnum = message.cseq;
}
else { // type is UAC, RFC 3261 12.1.2
this.id = {
callId: message.callId,
localTag: message.fromTag,
remoteTag: message.toTag,
toString: function () {
return message.callId + message.fromTag + message.toTag;
}
};
this.state = state;
this.inviteSeqnum = message.cseq;
this.localSeqnum = message.cseq;
this.localUri = message.parseHeader("from").uri;
this.pracked = [];
this.remoteUri = message.parseHeader("to").uri;
this.remoteTarget = contact.uri;
this.routeSet = message.getHeaders("record-route").reverse();
}
this.logger = owner.ua.getLogger("sip.dialog", this.id.toString());
this.owner = owner;
owner.ua.dialogs[this.id.toString()] = this;
this.logger.log("new " + type + " dialog created with status " +
(this.state === Enums_1.DialogStatus.STATUS_EARLY ? "EARLY" : "CONFIRMED"));
owner.emit("dialog", this);
}
/**
* @param {SIP.IncomingMessage} message
* @param {Enum} UAC/UAS
*/
Dialog.prototype.update = function (message, type) {
this.state = Enums_1.DialogStatus.STATUS_CONFIRMED;
this.logger.log("dialog " + this.id.toString() + " changed to CONFIRMED state");
if (type === "UAC") {
// RFC 3261 13.2.2.4
this.routeSet = message.getHeaders("record-route").reverse();
}
};
Dialog.prototype.terminate = function () {
this.logger.log("dialog " + this.id.toString() + " deleted");
if (this.sessionDescriptionHandler && this.state !== Enums_1.DialogStatus.STATUS_CONFIRMED) {
// TODO: This should call .close() on the handler when implemented
this.sessionDescriptionHandler.close();
}
delete this.owner.ua.dialogs[this.id.toString()];
};
/**
* @param {String} method request method
* @param {Object} extraHeaders extra headers
* @returns {SIP.OutgoingRequest}
*/
// RFC 3261 12.2.1.1
Dialog.prototype.createRequest = function (method, extraHeaders, body) {
if (extraHeaders === void 0) { extraHeaders = []; }
extraHeaders = extraHeaders.slice();
if (!this.localSeqnum) {
this.localSeqnum = Math.floor(Math.random() * 10000);
}
var cseq = (method === Constants_1.C.CANCEL || method === Constants_1.C.ACK) ? this.inviteSeqnum : this.localSeqnum += 1;
var request = new SIPMessage_1.OutgoingRequest(method, this.remoteTarget, this.owner.ua, {
cseq: cseq,
callId: this.id.callId,
fromUri: this.localUri,
fromTag: this.id.localTag,
toIri: this.remoteUri,
toTag: this.id.remoteTag,
routeSet: this.routeSet
}, extraHeaders, body);
request.dialog = this;
return request;
};
/**
* @param {SIP.IncomingRequest} request
* @returns {Boolean}
*/
// RFC 3261 12.2.2
Dialog.prototype.checkInDialogRequest = function (request) {
var _this = this;
if (!this.remoteSeqnum) {
this.remoteSeqnum = request.cseq;
}
else if (request.cseq < this.remoteSeqnum) {
// Do not try to reply to an ACK request.
if (request.method !== Constants_1.C.ACK) {
request.reply(500);
}
return request.cseq === this.inviteSeqnum;
}
switch (request.method) {
// RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-
case Constants_1.C.INVITE:
if (this.uacPendingReply === true) {
request.reply(491);
}
else if (this.uasPendingReply === true && request.cseq > this.remoteSeqnum) {
var retryAfter = Math.floor((Math.random() * 10)) + 1;
request.reply(500, undefined, ["Retry-After:" + retryAfter]);
this.remoteSeqnum = request.cseq;
return false;
}
else {
this.uasPendingReply = true;
var stateChanged_1 = function () {
if (request.serverTransaction &&
(request.serverTransaction.state === Enums_1.TransactionStatus.STATUS_ACCEPTED ||
request.serverTransaction.state === Enums_1.TransactionStatus.STATUS_COMPLETED ||
request.serverTransaction.state === Enums_1.TransactionStatus.STATUS_TERMINATED)) {
request.serverTransaction.removeListener("stateChanged", stateChanged_1);
_this.uasPendingReply = false;
}
};
if (request.serverTransaction) {
request.serverTransaction.on("stateChanged", stateChanged_1);
}
}
// RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted
if (request.hasHeader("contact") && request.serverTransaction) {
request.serverTransaction.on("stateChanged", function () {
if (request.serverTransaction && request.serverTransaction.state === Enums_1.TransactionStatus.STATUS_ACCEPTED) {
_this.remoteTarget = request.parseHeader("contact").uri;
}
});
}
break;
case Constants_1.C.NOTIFY:
// RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted
if (request.hasHeader("contact") && request.serverTransaction) {
request.serverTransaction.on("stateChanged", function () {
if (request.serverTransaction && request.serverTransaction.state === Enums_1.TransactionStatus.STATUS_COMPLETED) {
_this.remoteTarget = request.parseHeader("contact").uri;
}
});
}
break;
}
if (request.cseq > this.remoteSeqnum) {
this.remoteSeqnum = request.cseq;
}
return true;
};
Dialog.prototype.sendRequest = function (applicant, method, options) {
var _this = this;
if (options === void 0) { options = {}; }
var extraHeaders = (options.extraHeaders || []).slice();
var body;
if (options.body) {
if (options.body.body) {
body = options.body;
}
else {
body = {};
body.body = options.body;
if (options.contentType) {
body.contentType = options.contentType;
}
}
}
var request = this.createRequest(method, extraHeaders, body);
var dialogSend = function (reattempt) {
var requestSender = new RequestSender_1.RequestSender({
request: request,
onRequestTimeout: applicant.onRequestTimeout.bind(applicant),
onTransportError: applicant.onTransportError.bind(applicant),
receiveResponse: function (response) {
// RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog.
if (response.statusCode === 408 || response.statusCode === 481) {
applicant.onDialogError(response);
}
else if (response.method === Constants_1.C.INVITE && response.statusCode === 491) {
if (reattempt) {
applicant.receiveResponse(response);
}
else {
request.cseq = _this.localSeqnum += 1;
setTimeout(function () {
// first check is to determine !Subscription (remove circular dependency)
if (_this.owner.status !== undefined &&
_this.owner.status
!== Enums_1.SessionStatus.STATUS_TERMINATED) {
// RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
dialogSend(true);
}
}, 1000);
}
}
else {
applicant.receiveResponse(response);
}
}
}, _this.owner.ua);
requestSender.send();
// RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-
if (!requestSender.clientTransaction ||
requestSender.clientTransaction.type === Enums_1.TypeStrings.AckClientTransaction) {
return;
}
else if (request.method === Constants_1.C.INVITE &&
requestSender.clientTransaction &&
requestSender.clientTransaction.state
!== Enums_1.TransactionStatus.STATUS_TERMINATED) {
_this.uacPendingReply = true;
var stateChanged_2 = function () {
var state = requestSender.clientTransaction.state;
if (!requestSender.clientTransaction ||
requestSender.clientTransaction.type === Enums_1.TypeStrings.AckClientTransaction) {
return;
}
else if (requestSender.clientTransaction &&
(state === Enums_1.TransactionStatus.STATUS_ACCEPTED ||
state === Enums_1.TransactionStatus.STATUS_COMPLETED ||
state === Enums_1.TransactionStatus.STATUS_TERMINATED)) {
requestSender.clientTransaction.removeListener("stateChanged", stateChanged_2);
_this.uacPendingReply = false;
}
};
requestSender.clientTransaction.on("stateChanged", stateChanged_2);
}
};
dialogSend(false);
return request;
};
/**
* @param {SIP.IncomingRequest} request
*/
Dialog.prototype.receiveRequest = function (request) {
// Check in-dialog request
if (!this.checkInDialogRequest(request)) {
return;
}
this.owner.receiveRequest(request);
};
Dialog.C = Enums_1.DialogStatus;
return Dialog;
}());
exports.Dialog = Dialog;
|
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest( {
id: "15.9.5.43-0-1",
path: "TestCases/chapter15/15.9/15.9.5/15.9.5.43/15.9.5.43-0-1.js",
description: "Date.prototype.toISOString must exist as a function",
test: function testcase() {
var f = Date.prototype.toISOString;
if (typeof(f) === "function") {
return true;
}
}
});
|
var express = require("express");
var router = express.Router();
var burger = require("../models/burger.js");
// Create all our routes and set up logic within those routes where required.
router.get("/", function(req, res) {
burger.selectAll(function(data) {
var hbsObject = {
burgers: data
};
console.log(hbsObject);
res.render("index", hbsObject);
});
});
router.post("/api/burgers", function(req, res) {
burger.insertOne(
[req.body.name], function(result) {
res.json({ id: result.insertId });
});
});
router.put("/api/burgers/:id", function(req, res) {
var condition = "id = " + req.params.id;
console.log("condition", condition);
burger.updateOne({
devoured: req.body.devoured
}, condition, function(result) {
if (result.changedRows == 0) {
return res.status(404).end();
} else {
res.status(200).end();
}
});
});
module.exports = router; |
/*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.form.PasswordValidator"]){
dojo._hasResource["dojox.form.PasswordValidator"]=true;
dojo.provide("dojox.form.PasswordValidator");
dojo.require("dijit.form._FormWidget");
dojo.require("dijit.form.ValidationTextBox");
dojo.requireLocalization("dojox.form","PasswordValidator",null,"zh,ca,ROOT,pt,da,tr,ru,de,sv,ja,he,fi,nb,el,ar,pt-pt,cs,fr,es,ko,nl,zh-tw,pl,th,it,hu,sk,sl");
dojo.declare("dojox.form._ChildTextBox",dijit.form.ValidationTextBox,{containerWidget:null,type:"password",reset:function(){
dijit.form.ValidationTextBox.prototype._setValueAttr.call(this,"",true);
this._hasBeenBlurred=false;
}});
dojo.declare("dojox.form._OldPWBox",dojox.form._ChildTextBox,{_isPWValid:false,_setValueAttr:function(_1,_2){
if(_1===""){
_1=dojox.form._OldPWBox.superclass.attr.call(this,"value");
}
if(_2!==null){
this._isPWValid=this.containerWidget.pwCheck(_1);
}
this.inherited(arguments);
},isValid:function(_3){
return this.inherited("isValid",arguments)&&this._isPWValid;
},_update:function(e){
if(this._hasBeenBlurred){
this.validate(true);
}
this._onMouse(e);
},_getValueAttr:function(){
if(this.containerWidget._started&&this.containerWidget.isValid()){
return this.inherited(arguments);
}
return "";
}});
dojo.declare("dojox.form._NewPWBox",dojox.form._ChildTextBox,{required:true,onChange:function(){
this.containerWidget._inputWidgets[2].validate(false);
this.inherited(arguments);
}});
dojo.declare("dojox.form._VerifyPWBox",dojox.form._ChildTextBox,{isValid:function(_5){
return this.inherited("isValid",arguments)&&(this.attr("value")==this.containerWidget._inputWidgets[1].attr("value"));
}});
dojo.declare("dojox.form.PasswordValidator",dijit.form._FormValueWidget,{required:true,_inputWidgets:null,oldName:"",templateString:"<div dojoAttachPoint=\"containerNode\">\n\t<input type=\"hidden\" name=\"${name}\" value=\"\" dojoAttachPoint=\"focusNode\" />\n</div>\n",_hasBeenBlurred:false,isValid:function(_6){
return dojo.every(this._inputWidgets,function(i){
if(i&&i._setStateClass){
i._setStateClass();
}
return (!i||i.isValid());
});
},validate:function(_8){
return dojo.every(dojo.map(this._inputWidgets,function(i){
if(i&&i.validate){
i._hasBeenBlurred=(i._hasBeenBlurred||this._hasBeenBlurred);
return i.validate();
}
return true;
},this),"return item;");
},reset:function(){
this._hasBeenBlurred=false;
dojo.forEach(this._inputWidgets,function(i){
if(i&&i.reset){
i.reset();
}
},this);
},_createSubWidgets:function(){
var _b=this._inputWidgets,_c=dojo.i18n.getLocalization("dojox.form","PasswordValidator",this.lang);
dojo.forEach(_b,function(i,_e){
if(i){
var p={containerWidget:this},c;
if(_e===0){
p.name=this.oldName;
p.invalidMessage=_c.badPasswordMessage;
c=dojox.form._OldPWBox;
}else{
if(_e===1){
p.required=this.required;
c=dojox.form._NewPWBox;
}else{
if(_e===2){
p.invalidMessage=_c.nomatchMessage;
c=dojox.form._VerifyPWBox;
}
}
}
_b[_e]=new c(p,i);
}
},this);
},pwCheck:function(_11){
return false;
},postCreate:function(){
this.inherited(arguments);
var _12=this._inputWidgets=[];
dojo.forEach(["old","new","verify"],function(i){
_12.push(dojo.query("input[pwType="+i+"]",this.containerNode)[0]);
},this);
if(!_12[1]||!_12[2]){
throw new Error("Need at least pwType=\"new\" and pwType=\"verify\"");
}
if(this.oldName&&!_12[0]){
throw new Error("Need to specify pwType=\"old\" if using oldName");
}
this._createSubWidgets();
},_setDisabledAttr:function(_14){
this.inherited(arguments);
dojo.forEach(this._inputWidgets,function(i){
if(i&&i.attr){
i.attr("disabled",_14);
}
});
},_setRequiredAttribute:function(_16){
this.required=_16;
dojo.attr(this.focusNode,"required",_16);
dijit.setWaiState(this.focusNode,"required",_16);
this._refreshState();
dojo.forEach(this._inputWidgets,function(i){
if(i&&i.attr){
i.attr("required",_16);
}
});
},_getValueAttr:function(){
if(this.isValid()){
return this._inputWidgets[1].attr("value");
}
return "";
},focus:function(){
var f=false;
dojo.forEach(this._inputWidgets,function(i){
if(i&&!i.isValid()&&!f){
i.focus();
f=true;
}
});
if(!f){
this._inputWidgets[1].focus();
}
}});
}
|
import * as tslib_1 from "tslib";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Manager, Reference, Popper } from "react-popper";
import { observer } from "mobx-react";
import { DomNodeProxy } from "../util/react/DomNodeProxy";
import styled, { css } from "../styled-components";
const getArrowStyle = (placement, arrowSize, arrowColor) => {
let neutralBorder = arrowSize + "px solid transparent";
let colorBorder = arrowSize + "px solid " + arrowColor;
if (!placement) {
return ``;
}
if (placement.startsWith("top")) {
return css `
transform: translateX(-50%);
border-left: ${neutralBorder};
border-right: ${neutralBorder};
border-top: ${colorBorder};
`;
}
else if (placement.startsWith("bottom")) {
return css `
transform: translateX(-50%);
top: -${arrowSize}px;
border-left: ${neutralBorder};
border-right: ${neutralBorder};
border-bottom: ${colorBorder};
`;
}
else if (placement.startsWith("left")) {
return css `
transform: translateY(-50%);
right: -${arrowSize}px;
border-top: ${neutralBorder};
border-left: ${colorBorder};
border-bottom: ${neutralBorder};
`;
}
else if (placement.startsWith("right")) {
return css `
transform: translateY(-50%);
left: -${arrowSize}px;
border-top: ${neutralBorder};
border-right: ${colorBorder};
border-bottom: ${neutralBorder};
`;
}
else {
return ``;
}
};
const getArrowPosition = (placement) => {
if (!placement) {
return ``;
}
if (placement.startsWith("bottom")) {
return css `
top: 0;
`;
}
else if (placement.startsWith("left")) {
return css `
right: 0;
`;
}
else {
return ``;
}
};
const Arrow = styled("div").withConfig({ displayName: "Arrow", componentId: "sc-1pz3uns" }) `
position: absolute;
${props => getArrowPosition(props.placement)}
&:before, &:after {
content: "";
position: absolute;
}
&:before {
${props => props.borderColor ? getArrowStyle(props.placement, 6, props.borderColor) : ``}
}
&:after {
${props => getArrowStyle(props.placement, 5, props.backgroundColor)}
}
`;
let Popover = class Popover extends React.Component {
render() {
return (React.createElement(Manager, null,
React.createElement(Reference, null, ({ ref }) => React.createElement(DomNodeProxy, { onMount: el => ref(el), onUnmount: el => ref(null) }, this.props.children)),
this.props.visible ?
ReactDOM.createPortal(React.createElement(Popper, Object.assign({ placement: this.props.placement, modifiers: Object.assign({ offset: {
offset: `${this.props.alignmentOffset + "px" || 0}, ${this.props.offset}px`
} }, (this.props.noFlip ? { flip: { enabled: false } } : {})) }, (this.props.referenceElement ? { referenceElement: this.createReferenceObject() } : {})), ({ ref, style, placement, arrowProps }) => (React.createElement("div", { ref: ref, onClick: e => e.stopPropagation(), style: Object.assign({}, style, { background: this.props.backgroundColor, boxShadow: "0 2px 6px 0 rgba(0, 0, 0, .08)", border: this.props.borderColor ? "1px solid " + this.props.borderColor : void 0, boxSizing: "border-box", pointerEvents: this.props.nonInteractive ? "none" : void 0 }, this.props.style), "data-placement": placement },
this.props.content,
!this.props.noArrow ?
React.createElement(Arrow, { placement: placement, backgroundColor: this.props.backgroundColor, borderColor: this.props.borderColor, innerRef: arrowProps.ref, style: arrowProps.style })
: null))), document.body)
: null));
}
createReferenceObject() {
let referenceEl = this.props.referenceElement;
if (typeof referenceEl !== "function") {
return referenceEl;
}
const getWrapperEl = referenceEl;
return {
getBoundingClientRect() {
return getWrapperEl() ? getWrapperEl().getBoundingClientRect() :
{ bottom: 0, left: 0, right: 0, top: 0, height: 0, width: 0 };
},
get clientWidth() {
return getWrapperEl() ? getWrapperEl().clientWidth : 0;
},
get clientHeight() {
return getWrapperEl() ? getWrapperEl().clientHeight : 0;
}
};
}
};
Popover.defaultProps = {
backgroundColor: "#fff",
placement: "top",
offset: 0
};
Popover = tslib_1.__decorate([
observer
], Popover);
export { Popover };
//# sourceMappingURL=Popover.js.map |
window._ = require('lodash');
window.Popper=require('popper.js').default;
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
require('admin-lte');
} catch (e) {}
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });
|
import logging
import os
import re
import cv2
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
class FolderStructure:
def __init__(self, config):
self.config = config
self.output_dir = self.config['PATHS']['output_folder']
self.output_folder_is_exist = os.path.exists(self.output_dir)
self.label_required_folder = self.config['PATHS']['label_required_folder_name']
self.input_folder = self.config['PATHS']['input_folder']
self.current_structure = {}
self.unsuccessful_folder = None
def sync_with_db(self, db_object):
"""
| Create or update folder structure in 'output_folder'
| according to DB structure.
| Remember: DB is MASTER, folder structure is SLAVE
"""
self.db = db_object
if self.output_folder_is_exist:
self.__update_structure()
else:
self.__create_structure()
def get_current_structure(self):
self.__get_current_structure()
return self.current_structure
def move_to_unsuccessful(self, file_path):
if not self.unsuccessful_folder:
self.__create_unsuccessful_dir()
os.replace(
file_path,
# could not working on windows:
os.path.join(self.unsuccessful_folder, os.path.basename(file_path))
)
def dispose_original(self, image):
if int(self.config['MAIN']['delete_processed_files']):
os.remove(image.path_to_original)
else:
self.__create_successful_dir()
os.replace(
image.path_to_original,
os.path.join(
self.successful_folder,
os.path.basename(image.path_to_original)
)
)
@staticmethod
def __create_photo_filename(uid: str, dt, extension):
filename_list = [
uid,
dt.strftime('%Y-%m-%d_%H-%M-%S')
]
filename_str = '_'.join(filename_list)
filename_str += extension
return filename_str
def __get_output_path_by_uid(self, uid):
# self.__update_structure() # what for?
path = os.path.join(
self.output_dir,
self.current_structure[uid],
)
return path
def save_image_to_output(self, image):
if image.decoded_uids:
for uid in image.decoded_uids:
if uid in self.current_structure:
filename, file_extension = os.path.splitext(image.path_to_original)
file_name = self.__create_photo_filename(
uid,
image.shooting_date,
file_extension
)
file_path = os.path.join(
self.__get_output_path_by_uid(uid),
file_name
)
cv2.imwrite(file_path, image.output_image)
logger.info('Saved image: %s', file_path)
else:
logger.warning("Can't save file, unknown UID:", uid)
def __create_successful_dir(self):
self.successful_folder = os.path.join(self.input_folder, 'successful')
if not os.path.exists(self.successful_folder):
os.mkdir(self.successful_folder)
def __create_unsuccessful_dir(self):
self.unsuccessful_folder = os.path.join(self.input_folder, 'unsuccessful')
if not os.path.exists(self.unsuccessful_folder):
os.mkdir(self.unsuccessful_folder)
def __create_folder_item_name(self, item):
name_list = []
# UID|number|genus|species|subspecies|variety|cultivar|synonym|form|affinity|ex|information|source|seeding_date|purchase_date|pot_width|pot_height|soil|description
fields = ['UID', 'number', 'genus', 'species', 'subspecies', 'variety', 'cultivar', 'synonym']
for f in fields:
if f in item:
value = item[f].replace(' ', '-')
name_list.append(value)
name_str = '_'.join(name_list)
return name_str
def __create_item_folder(self, item):
if item and 'UID' in item:
folder_name = self.__create_folder_item_name(item)
item_folder_path = os.path.join(self.output_dir, folder_name)
os.makedirs(item_folder_path)
manual_folder_path = os.path.join(item_folder_path, self.label_required_folder)
os.makedirs(manual_folder_path)
def __create_structure(self):
# create main output folder
os.makedirs(self.output_dir)
# create inner folder structure
db_data = self.db.get_data()
for uid in db_data:
self.__create_item_folder(db_data[uid])
def __get_current_structure(self):
# get current folder structure
pattern = r"^(\d+)_.+$"
output_dir_ls = os.listdir(self.output_dir)
for folder in output_dir_ls:
folder_path = os.path.join(self.output_dir, folder)
if os.path.exists(folder_path):
uid_search = re.search(pattern, folder)
if uid_search:
uid = uid_search.group(1)
self.current_structure[uid] = folder
else:
logger.warning('Foreign directory in output folder: %s', folder)
else:
logger.warning('Foreign object in output folder: %s', folder)
def __update_structure(self):
self.__get_current_structure()
# check each item from db: if it exist (by UID) and compare full folder names
db_data = self.db.get_data()
for uid in db_data:
if uid in self.current_structure:
folder_name_current = self.current_structure[uid]
folder_name_should_be = self.__create_folder_item_name(db_data[uid])
if folder_name_current != folder_name_should_be:
os.rename(
os.path.join(self.output_dir, folder_name_current),
os.path.join(self.output_dir, folder_name_should_be)
)
logger.info('Name of folder was changed for UID: %s', uid)
else:
if re.match(r'\d+', uid):
self.__create_item_folder(db_data[uid])
logger.info('Folder for UID: %s was not found. Now created', uid)
def main():
fs = FolderStructure('../OUTPUT')
if __name__ == '__main__':
main()
|
var callbackArguments = [];
var argument1 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument3[0] = ""
argument2[5] = ""
base_0[8] = 893
return a+b+c/d
};
var argument2 = "";
var argument3 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument5 = "Q"
argument4[4] = null
argument5[6] = null
return a*b/c*d
};
var argument4 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
base_2[5] = null
argument6[3] = null
base_2[2] = true
return a/b-c+d
};
var argument5 = 7.031014235045233e+307;
var argument6 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument7[4] = {"":714}
base_3[5] = 2.667893647622747e+307
return a-b*c*d
};
var argument7 = null;
var base_0 = ["*I","}Q","V","{"]
var r_0= undefined
try {
r_0 = base_0.reduceRight(argument1,argument2)
}
catch(e) {
r_0= "Error"
}
var base_1 = ["*I","}Q","V","{"]
var r_1= undefined
try {
r_1 = base_1.reduceRight(argument3)
}
catch(e) {
r_1= "Error"
}
var base_2 = ["*I","}Q","V","{"]
var r_2= undefined
try {
r_2 = base_2.reduceRight(argument4,argument5)
}
catch(e) {
r_2= "Error"
}
var base_3 = ["*I","}Q","V","{"]
var r_3= undefined
try {
r_3 = base_3.reduceRight(argument6,argument7)
}
catch(e) {
r_3= "Error"
}
function serialize(array){
return array.map(function(a){
if (a === null || a == undefined) return a;
var name = a.constructor.name;
if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String')
return JSON.stringify(a);
return name;
});
}
setTimeout(function(){
require("fs").writeFileSync("./experiments/reduceRight/reduceRightGen/test119.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments}))
},300) |
#!/usr/bin/env python3
import math
import rospy
from std_msgs.msg import String
# from gomoku_ik.msg import Pose4D
# from gomoku_ik.msg import Joint_msg
from std_msgs.msg import Float32MultiArray
from gomoku_ik_solver.gomoku_ik_solver import ik_gomoku
import numpy as np
from std_srvs.srv import *
class ik_calc():
def __init__(self):
self.pub = rospy.Publisher('/joint_goal', Float32MultiArray, queue_size=10)
rospy.Subscriber("/robot_move", Float32MultiArray, self.ik_callback)
self.ik_object = ik_gomoku()
self.board_z = 100 #100mm
self.length_side = 33 # the side of each square is 33mm
self.x_offset = 84.2
self.y_offset = -148.5
self.z_offset = -28.38
self.default_position = [50,-100,170]
self.intermediate_position = [50, -255, 160]
self.intermediate_position_bef_grip = [30, -255, 160]
self.feeder_position = [30, -255, 110]
print("Initialised")
def board_pos_to_coord(self,msg):
x_board = msg.data[0]*self.length_side + self.x_offset
y_board = msg.data[1]*self.length_side + self.y_offset
return (x_board,y_board)
def call_serv(self):
rospy.wait_for_service('/trigger_movement')
try:
trigger_obj = rospy.ServiceProxy('/trigger_movement', Trigger)
resp1 = trigger_obj()
return resp1.success
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def move_to(self, values, gripper_motion, orient = None):
# coordinates to joint values
joint_angles_dict = self.coord_to_angles(values, orient)
joint_angles_list = [joint_angles_dict['joint_1'],joint_angles_dict['joint_2'],joint_angles_dict['joint_3'],joint_angles_dict['gripper_joint']]
joint_angles_list.append(gripper_motion)
pub_msg = Float32MultiArray()
pub_msg.data = joint_angles_list
# 1 -- open(drop), 2 -- close(pick), 0 -- wait
self.pub.publish(pub_msg)
return self.call_serv()
def coord_to_angles(self, coord, orient = None):
x = coord[0]
y = coord[1]
z = coord[2]
self.ik_object.position_endeff['x'] = x
self.ik_object.position_endeff['y'] = y
self.ik_object.position_endeff['z'] = z
self.ik_object.set_orient = orient
return self.ik_object.calculate_joint_values()
def ik_callback(self,msg):
x,y = self.board_pos_to_coord(msg)
z = self.z_offset
print("Given pose: x:{0} y:{1} z:{2} ".format(x,y,z))
# get gripper orient of board position from ik first
self.ik_object.position_endeff['x'] = x
self.ik_object.position_endeff['y'] = y
self.ik_object.position_endeff['z'] = z
self.ik_object.calculate_joint_values()
print("X: {0} Y: {1} Z: {2}".format(x,y,z))
orient = self.ik_object.get_orient()
board_position = [x,y,z]
intermediate_before_grip = self.intermediate_position_bef_grip
feeder_position = self.feeder_position
intermediate = self.intermediate_position
if orient == "h":
# z
feeder_position[2] -= 13
board_position[2] += 20
# y
intermediate_before_grip[1] -= 24
feeder_position[1] -= 24
intermediate[1] -= 24
board_position[1] += 33
# x
board_position[0] += 36
intermediate_above_board = [board_position[0],board_position[1],board_position[2]+20]
moved_to_intermediate_initial = self.move_to(intermediate_before_grip, 1, orient = orient)
moved_to_feeder = self.move_to(feeder_position, 2, orient = orient)
if(moved_to_feeder):
moved_to_intermediate = self.move_to(intermediate, 2, orient = orient)
input(
"============ Press `Enter` to go to the board position ..."
)
if moved_to_intermediate:
# moving to board
moved_to_board = self.move_to(board_position, 1,orient=orient)
# input(
# "============ Press `Enter` to go to the default position ..."
# )
if moved_to_board:
# moving to default
if(orient == "h"):
moved_to_intermediate = self.move_to(intermediate_above_board, 2, orient = orient)
moved_to_default = self.move_to(self.default_position, 1,orient=orient)
if moved_to_default:
print("Back to home")
############ TO ADD ###############
#Go to feeder and wait
def main(args=None):
rospy.init_node('gomoku_ik_node')
ik_calc()
rospy.spin()
if __name__ == '__main__':
main() |
var searchData=
[
['deletefirstnode_102',['deleteFirstNode',['../class_simple_list.html#ada0e1d3b9b10f475ea0ea2d3a2101383',1,'SimpleList']]],
['deletelastnode_103',['deleteLastNode',['../class_simple_list.html#a9d6c9e5558b506b07c61ea65300fdff9',1,'SimpleList']]],
['deletenode_104',['deleteNode',['../class_simple_list.html#aac576fe0c08985ff27d783ff3849514f',1,'SimpleList']]],
['deletenodeat_105',['deleteNodeAt',['../class_simple_list.html#a0bc70c2b1113e4fefdff947864224665',1,'SimpleList']]]
];
|
import numpy as np
from vg.compat import v2 as vg
def percentile(points, axis, percentile):
"""
Given a cloud of points and an axis, find a point along that axis
from the centroid at the given percentile.
Args:
points (np.arraylike): A `kx3` stack of points.
axis (np.arraylike): A 3D vector specifying the direction of
interest.
percentile (float): The desired percentile.
Returns:
np.ndarray: A 3D point at the requested percentile.
"""
k = vg.shape.check(locals(), "points", (-1, 3))
if k < 1:
raise ValueError("At least one point is needed")
vg.shape.check(locals(), "axis", (3,))
if vg.almost_zero(axis):
raise ValueError("Axis must be non-zero")
axis = vg.normalize(axis)
coords_on_axis = points.dot(axis)
selected_coord_on_axis = np.percentile(coords_on_axis, percentile)
centroid = np.average(points, axis=0)
return vg.reject(centroid, axis) + selected_coord_on_axis * axis
def extent(points, ret_indices=False):
"""
Find the distance between the two farthest-most points.
Args:
points (np.arraylike): A `kx3` stack of points.
ret_indices (bool): When `True`, return the indices along with the
distance.
Returns:
object: With `ret_indices=False`, the distance; with
`ret_indices=True` a tuple `(distance, first_index, second_index)`.
Note:
This is implemented using a brute-force method.
"""
k = vg.shape.check(locals(), "points", (-1, 3))
if k < 2:
raise ValueError("At least two points are required")
farthest_i = -1
farthest_j = -1
farthest_distance = -1
for i, probe in enumerate(points):
distances = vg.euclidean_distance(points, probe)
this_farthest_j = np.argmax(distances)
if distances[this_farthest_j] > farthest_distance:
farthest_i = i
farthest_j = this_farthest_j
farthest_distance = distances[this_farthest_j]
if ret_indices:
return farthest_distance, farthest_i, farthest_j
else:
return farthest_distance
|
"""
Routines for reading an LCModel *.RAW file. Note that this can ONLY happen
if there is already a dataset loaded from which we can 'steal' the SW, and
DIM0 and other parameters.
"""
# Python modules
from __future__ import division
import os.path
# 3rd party modules
import numpy as np
# Our modules
import vespa.common.constants as constants
import vespa.common.util.misc as util_misc
import vespa.common.mrs_data_raw as mrs_data_raw
import vespa.common.configobj as configobj
import vespa.analysis.fileio.raw_reader as raw_reader
# data is complex64 per Philips documentation for SDAT
NUMPY_DATA_TYPE = np.complex64
class LCModelRawHardcode(raw_reader.RawReader):
# This inherits from raw_reader.RawReader (q.v.). The only methods you
# need to implement are __init__() and read_raw(). You *may* want to
# override or supplement some of raw_reader.RawReader's other methods.
def __init__(self):
raw_reader.RawReader.__init__(self)
self.filetype_filter = "LCMode RAW (*.RAW)|*.raw;*.RAW;"
self.multiple = False
def read_raw(self, filename, ignore_data=False, open_dataset=None):
"""
Given the name of a .spar or .sdat file, returns a DataRawFidSum object
populated with the parameters and data represented by the file pair.
When ignore_data is True, this function only reads the parameters file
which can be much faster than reading both params & data.
"""
# must have an open dataset to borrow parameters from
if open_dataset is None:
raise raw_reader.OpenFileUserReadRawError("No open datasets, can not import/convert LCModel RAW file")
# Read the SPAR file and extract the stuff I need.
lines = open(filename, "rb").read()
# Now we find the start/end of the header section based on the standard
# ">>> Begin of header <<<" and ">>> End of header <<<" marker lines
istr = lines.find("$NMID")
iend = lines.find("$END")
head_only = lines[istr+5:iend] # save this to return to user
data_only = lines[iend+4:]
data = util_misc.normalize_newlines(data_only)
data = data.replace("\n"," ")
data = data.replace(" "," ")
data = data.split(" ")
data = [float(val)for val in data if util_misc.is_floatable(val) ]
data = np.array(data)
data = data.astype(dtype=np.float32).view(np.complex64)
if data.shape[0] != open_dataset.raw_dims[0]:
data = data[0:open_dataset.raw_dims[0]]
d = { }
d['headers'] = head_only
d["data_source"] = filename
d["sequence_type"] = "semi-laser"
d["frequency"] = open_dataset.frequency # 123.244349
d["sw"] = open_dataset.sw # 6002.44
d["dims"] = [1024,1,1,1]
d["dims"][0] = data.shape[-1]
d["nucleus"] = open_dataset.nucleus # '1H'
d["seqte"] = open_dataset.seqte # 35.0
# Create a DataRaw out of the first set of data in the list.
d["data"] = data #/ 10000.0 # empirical to allow area param to be larger
raw = mrs_data_raw.DataRaw(d)
return [raw,]
#################### Internal functions start here ###############
|
const nforce = require('../');
const auth={};
async function authenticate(){
const sfuser = process.env.SFUSER;
const sfpass = process.env.SFPASS;
const clientID = process.env.CLIENTID;
const clientSecret = process.env.CLIENTSECRET;
if(!auth.org){
console.log("authenticating");
auth.org = nforce.createConnection({
clientId: clientID,
clientSecret: clientSecret,
redirectUri: 'http://localhost:3000/oauth/_callback'
});
auth.oauth = await auth.org.authenticate({ username: sfuser, password: sfpass});
console.log(JSON.stringify(auth.oauth));
}
}
async function getList(){
await authenticate();
var query = 'SELECT FirstName, LastName FROM Contact';
console.log("Authenticated");
if(!auth.oauth) return [];
console.log(JSON.stringify(auth.oauth));
console.log("Querying");
resp = await auth.org.query({ query: query, oauth: auth.oauth });
console.log("Queried");
console.log('Query returned: ' + resp.records.length + ' records');
if(resp.records && resp.records.length) {
resp.records.forEach(function(rec) {
console.log('Contact: ' + rec.get('FirstName') + ' ' + rec.get('LastName'));
});
}
return (resp.records);
}
async function waitForList(){
var start = Date.now();
console.log("getting list");
for(i=0;i<10;i++)
await getList();
console.log("got list");
console.log("seconds elapsed = " + Math.floor((Date.now()-start)/1000));
}
waitForList();
|
# -*- coding: utf-8 -*-
# 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.
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'openstackdocstheme',
'reno.sphinxext',
]
# openstackdocstheme options
openstackdocs_repo_name = 'openstack/kolla-ansible'
openstackdocs_bug_project = 'kolla-ansible'
openstackdocs_bug_tag = ''
openstackdocs_auto_name = False
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Kolla Ansible Release Notes'
copyright = '2015-2021, Kolla Ansible developers'
# Release notes do not need a version number in the title, they
# cover multiple releases.
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'native'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'openstackdocs'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'KollaAnsibleReleaseNotesdoc'
# -- Options for LaTeX output ---------------------------------------------
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'KollaAnsibleReleaseNotes.tex',
'Kolla Ansible Release Notes Documentation',
'Kolla Ansible developers', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'KollaAnsibleReleaseNotes',
'Kolla Ansible Release Notes Documentation',
'Kolla Ansible developers', 'KollaAnsibleReleaseNotes',
'Kolla-Ansible deploys OpenStack services and infrastructure components '
'in Docker containers.', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# -- Options for Internationalization output ------------------------------
locale_dirs = ['locale/']
|
'use strict';
const assert = require("assert");
const stateVariable = require("./element-state-variable.js");
const gc = require("./gc.js");
module.exports = {
codeExternal: function(node, history, parent) {
return "";
},
code: function(node, history, parent) {
assert(node);
assert(!(node instanceof Array));
let goCode = "type " + node.name;
goCode += gc.suffixContract ? "_" + parent.name : "";
goCode += " struct {\n";
for (let body of node.body) {
goCode += "\t" + stateVariable.code(body, history, parent, node) + "\n"
}
goCode += "}\n";
return goCode;
},
}; |
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class ImageDemo extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('ImageDemo', () => ImageDemo);
|
var searchData=
[
['tolowercase',['toLowerCase',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classutil_1_1Strings.html#a111a9ac8088ec56d3a109b95d43f654a',1,'util::Strings']]],
['top',['top',['../classRuntimeStack.html#a8b6e80ccca40a8445d1c7329248d19e8',1,'RuntimeStack']]],
['tostring',['toString',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classObject.html#a2a71a6af528b14988cbf837b1d2861c6',1,'Object::toString()'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeNode.html#a652d0e9aaa8872b23a243cd3c6f99364',1,'TreeNode::toString()'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeNode.html#a652d0e9aaa8872b23a243cd3c6f99364',1,'VisitedTreeNode::toString()'],['../classDataBindingUtils.html#ad7ed78891bc4bf45b914f002d0ea13e1',1,'DataBindingUtils::toString()'],['../classRuntimeData.html#aed4111e8de3e9888d02c7b741aab451b',1,'RuntimeData::toString()'],['../classSourceCodePosition.html#a82d00605164d12ec3a8c192157e48e10',1,'SourceCodePosition::toString()'],['../classRuntimeStack.html#a6495bebbe9cdd605575f9e0b88a017bf',1,'RuntimeStack::toString()'],['../classSimpleSymbolTable.html#aa48bc3bb567a5b314db523f2a9513e32',1,'SimpleSymbolTable::toString()'],['../classSymbol.html#af5ccb3fb3201fd88ab6ce0e495416c82',1,'Symbol::toString()'],['../classSymbolRepository.html#a7a0fe23b5145248833981f3cbebefc57',1,'SymbolRepository::toString()'],['../classSymbolTableStack.html#a887e1e24dee78cd25ca941a85e3e39f5',1,'SymbolTableStack::toString()'],['../classStringAppender.html#aea5101e39f24292ab60bf4e42e10452b',1,'StringAppender::toString()']]],
['totree',['toTree',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeBuilder.html#a4510e315708948c5234aee5e2248aa4b',1,'TreeBuilder']]],
['touppercase',['toUpperCase',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classutil_1_1Strings.html#a650abf9821e56d30b505f52c56d6ad64',1,'util::Strings']]],
['translate',['translate',['../classParseExceptionTranslator.html#af7d4747bc0d23b4116af3b50e5217406',1,'ParseExceptionTranslator']]],
['treebuilder',['TreeBuilder',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeBuilder.html',1,'TreeBuilder< class, class >'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeBuilder.html#a0f9f3257a89f5c6c3d3223bd3f2983e1',1,'TreeBuilder::TreeBuilder()'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeBuilder.html#a20ebb04ed365ca584aafe48b9ae46369',1,'TreeBuilder::TreeBuilder(NodePtrType that)']]],
['treebuilder_2ecpp',['TreeBuilder.cpp',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeBuilder_8cpp.html',1,'']]],
['treebuilder_2eh',['TreeBuilder.h',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeBuilder_8h.html',1,'']]],
['treecontext_2eh',['TreeContext.h',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeContext_8h.html',1,'']]],
['treenode',['TreeNode',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeNode.html',1,'TreeNode'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeNode.html#a984a98d5ccf7ef1f5a18094c6821f35d',1,'TreeNode::TreeNode()'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeNode.html#ae8502e25e5b5abb5b94cd62cd20a410c',1,'TreeNode::TreeNode(TreeNode *const)'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeNode.html#ad4b92345703cf72ea1f0f2f5351587c8',1,'TreeNode::TreeNode(TreeNodePtr that)']]],
['treenode_2ecpp',['TreeNode.cpp',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeNode_8cpp.html',1,'']]],
['treenode_2eh',['TreeNode.h',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeNode_8h.html',1,'']]],
['treetraverse',['TreeTraverse',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeTraverse.html',1,'TreeTraverse'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeTraverse.html#ae1d8d125ded83054c23fc7601f5bfdc0',1,'TreeTraverse::TreeTraverse()']]],
['treetraverse_2ecpp',['TreeTraverse.cpp',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeTraverse_8cpp.html',1,'']]],
['treetraverse_2eh',['TreeTraverse.h',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeTraverse_8h.html',1,'']]],
['treewalker',['TreeWalker',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeWalker.html',1,'TreeWalker'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTreeWalker.html#ae0ee9fa909d78735790a9cd721e1cb90',1,'TreeWalker::TreeWalker()']]],
['treewalker_2eh',['TreeWalker.h',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/TreeWalker_8h.html',1,'']]],
['type',['type',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/structHackProxy.html#a85aebaf9ad69c6a89a7e57434cc41bd9',1,'HackPrivate::type()'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/structHackProxy.html#a85aebaf9ad69c6a89a7e57434cc41bd9',1,'HackProxy::type()']]],
['typecastexception',['TypeCastException',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTypeCastException.html',1,'TypeCastException'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/classTypeCastException.html#a575bd9dc0eda2a9bb98b56ce927894bd',1,'TypeCastException::TypeCastException()']]]
];
|
'use strict';
let geocoder;
let directions;
/** Initializes Google Maps API objects (geocoder, directions). */
function initGmaps() { // eslint-disable-line no-unused-vars
console.log('Maps initialized.');
geocoder = new google.maps.Geocoder();
console.log('Geocoder object: ' + geocoder);
directions = new google.maps.DirectionsService();
console.log('Directions object: ' + directions);
}
|
from frame import *
from mm_math import *
from convert import *
from util import *
from scene import *
from tool import *
from selection import *
from external import * |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = require("react");
var ItemShape =
/*#__PURE__*/
function (_PureComponent) {
(0, _inherits2.default)(ItemShape, _PureComponent);
function ItemShape() {
(0, _classCallCheck2.default)(this, ItemShape);
return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ItemShape).apply(this, arguments));
}
(0, _createClass2.default)(ItemShape, [{
key: "render",
value: function render() {
return null;
}
}]);
return ItemShape;
}(_react.PureComponent);
exports.default = ItemShape;
(0, _defineProperty2.default)(ItemShape, "defaultProps", {
isDisabled: false,
isSelected: false
}); |
import Vue from 'vue'
import * as api from '@/api/api'
import { isURL } from '@/utils/validate'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import onlineCommons from '@jeecg/antd-online-mini'
export function getQueryString(parameter) {
return new URL(window.location.href).searchParams.get(parameter)
}
export function timeFix() {
const time = new Date()
const hour = time.getHours()
return hour < 9 ? '早上好' : (hour <= 11 ? '上午好' : (hour <= 13 ? '中午好' : (hour < 20 ? '下午好' : '晚上好')))
}
export function welcome() {
const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
let index = Math.floor((Math.random()*arr.length))
return arr[index]
}
/**
* 触发 window.resize
*/
export function triggerWindowResizeEvent() {
let event = document.createEvent('HTMLEvents')
event.initEvent('resize', true, true)
event.eventType = 'message'
window.dispatchEvent(event)
}
/**
* 过滤对象中为空的属性
* @param obj
* @returns {*}
*/
export function filterObj(obj) {
if (!(typeof obj == 'object')) {
return;
}
for ( let key in obj) {
if (obj.hasOwnProperty(key)
&& (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
delete obj[key];
}
}
return obj;
}
/**
* 时间格式化
* @param value
* @param fmt
* @returns {*}
*/
export function formatDate(value, fmt) {
let regPos = /^\d+(\.\d+)?$/;
if(regPos.test(value)){
//如果是数字
let getDate = new Date(value);
let o = {
'M+': getDate.getMonth() + 1,
'd+': getDate.getDate(),
'h+': getDate.getHours(),
'm+': getDate.getMinutes(),
's+': getDate.getSeconds(),
'q+': Math.floor((getDate.getMonth() + 3) / 3),
'S': getDate.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt;
}else{
//TODO
value = value.trim();
return value.substr(0,fmt.length);
}
}
// 生成首页路由
export function generateIndexRouter(data) {
let indexRouter = [{
path: '/',
name: 'dashboard',
//component: () => import('@/components/layouts/BasicLayout'),
component: resolve => require(['@/components/layouts/TabLayout'], resolve),
meta: { title: '首页' },
redirect: '/dashboard/analysis',
children: [
...generateChildRouters(data)
]
},{
"path": "*", "redirect": "/404", "hidden": true
}]
return indexRouter;
}
// 生成嵌套路由(子路由)
function generateChildRouters (data) {
const routers = [];
for (let item of data) {
let component = "";
if(item.component.indexOf("layouts")>=0){
component = "components/"+item.component;
}else{
component = "views/"+item.component;
}
// eslint-disable-next-line
let URL = (item.meta.url|| '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
if (isURL(URL)) {
item.meta.url = URL;
}
let componentPath
if(item.component=="modules/online/cgform/OnlCgformHeadList"){
componentPath = onlineCommons.OnlCgformHeadList
}else if(item.component=="modules/online/cgform/OnlCgformCopyList"){
componentPath = onlineCommons.OnlCgformCopyList
}else if(item.component=="modules/online/cgform/auto/OnlCgformAutoList"){
componentPath = onlineCommons.OnlCgformAutoList
}else if(item.component=="modules/online/cgform/auto/OnlCgformTreeList"){
componentPath = onlineCommons.OnlCgformTreeList
}else if(item.component=="modules/online/cgform/auto/erp/OnlCgformErpList"){
componentPath = onlineCommons.OnlCgformErpList
}else if(item.component=="modules/online/cgform/auto/tab/OnlCgformTabList"){
componentPath = onlineCommons.OnlCgformTabList
}else if(item.component=="modules/online/cgform/auto/innerTable/OnlCgformInnerTableList"){
componentPath = onlineCommons.OnlCgformInnerTableList
}else if(item.component=="modules/online/cgreport/OnlCgreportHeadList"){
componentPath = onlineCommons.OnlCgreportHeadList
}else if(item.component=="modules/online/cgreport/auto/OnlCgreportAutoList"){
componentPath = onlineCommons.OnlCgreportAutoList
}else{
componentPath = resolve => require(['@/' + component+'.vue'], resolve)
}
let menu = {
path: item.path,
name: item.name,
redirect:item.redirect,
component: componentPath,
//component: resolve => require(['@/' + component+'.vue'], resolve),
hidden:item.hidden,
//component:()=> import(`@/views/${item.component}.vue`),
meta: {
title:item.meta.title ,
icon: item.meta.icon,
url:item.meta.url ,
permissionList:item.meta.permissionList,
keepAlive:item.meta.keepAlive,
/*update_begin author:wuxianquan date:20190908 for:赋值 */
internalOrExternal:item.meta.internalOrExternal,
/*update_end author:wuxianquan date:20190908 for:赋值 */
componentName:item.meta.componentName
}
}
if(item.alwaysShow){
menu.alwaysShow = true;
menu.redirect = menu.path;
}
if (item.children && item.children.length > 0) {
menu.children = [...generateChildRouters( item.children)];
}
//--update-begin----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------
//判断是否生成路由
if(item.route && item.route === '0'){
//console.log(' 不生成路由 item.route: '+item.route);
//console.log(' 不生成路由 item.path: '+item.path);
}else{
routers.push(menu);
}
//--update-end----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------
}
return routers
}
/**
* 深度克隆对象、数组
* @param obj 被克隆的对象
* @return 克隆后的对象
*/
export function cloneObject(obj) {
return JSON.parse(JSON.stringify(obj))
}
/**
* 随机生成数字
*
* 示例:生成长度为 12 的随机数:randomNumber(12)
* 示例:生成 3~23 之间的随机数:randomNumber(3, 23)
*
* @param1 最小值 | 长度
* @param2 最大值
* @return int 生成后的数字
*/
export function randomNumber() {
// 生成 最小值 到 最大值 区间的随机数
const random = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min)
}
if (arguments.length === 1) {
let [length] = arguments
// 生成指定长度的随机数字,首位一定不是 0
let nums = [...Array(length).keys()].map((i) => (i > 0 ? random(0, 9) : random(1, 9)))
return parseInt(nums.join(''))
} else if (arguments.length >= 2) {
let [min, max] = arguments
return random(min, max)
} else {
return Number.NaN
}
}
/**
* 随机生成字符串
* @param length 字符串的长度
* @param chats 可选字符串区间(只会生成传入的字符串中的字符)
* @return string 生成的字符串
*/
export function randomString(length, chats) {
if (!length) length = 1
if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm'
let str = ''
for (let i = 0; i < length; i++) {
let num = randomNumber(0, chats.length - 1)
str += chats[num]
}
return str
}
/**
* 随机生成uuid
* @return string 生成的uuid
*/
export function randomUUID() {
let chats = '0123456789abcdef'
return randomString(32, chats)
}
/**
* 下划线转驼峰
* @param string
* @returns {*}
*/
export function underLine2CamelCase(string){
return string.replace( /_([a-z])/g, function( all, letter ) {
return letter.toUpperCase();
});
}
/**
* 判断是否显示办理按钮
* @param bpmStatus
* @returns {*}
*/
export function showDealBtn(bpmStatus){
if(bpmStatus!="1"&&bpmStatus!="3"&&bpmStatus!="4"){
return true;
}
return false;
}
/**
* 增强CSS,可以在页面上输出全局css
* @param css 要增强的css
* @param id style标签的id,可以用来清除旧样式
*/
export function cssExpand(css, id) {
let style = document.createElement('style')
style.type = "text/css"
style.innerHTML = `@charset "UTF-8"; ${css}`
// 清除旧样式
if (id) {
let $style = document.getElementById(id)
if ($style != null) $style.outerHTML = ''
style.id = id
}
// 应用新样式
document.head.appendChild(style)
}
/** 用于js增强事件,运行JS代码,可以传参 */
// options 所需参数:
// 参数名 类型 说明
// vm VueComponent vue实例
// event Object event对象
// jsCode String 待执行的js代码
// errorMessage String 执行出错后的提示(控制台)
export function jsExpand(options = {}) {
// 绑定到window上的keyName
let windowKeyName = 'J_CLICK_EVENT_OPTIONS'
if (typeof window[windowKeyName] != 'object') {
window[windowKeyName] = {}
}
// 随机生成JS增强的执行id,防止冲突
let id = randomString(16, 'qwertyuioplkjhgfdsazxcvbnm'.toUpperCase())
// 封装按钮点击事件
let code = `
(function (o_${id}) {
try {
(function (globalEvent, vm) {
${options.jsCode}
})(o_${id}.event, o_${id}.vm)
} catch (e) {
o_${id}.error(e)
}
o_${id}.done()
})(window['${windowKeyName}']['EVENT_${id}'])
`
// 创建script标签
const script = document.createElement('script')
// 将需要传递的参数挂载到window对象上
window[windowKeyName]['EVENT_' + id] = {
vm: options.vm,
event: options.event,
// 当执行完成时,无论如何都会调用的回调事件
done() {
// 执行完后删除新增的 script 标签不会撤销执行结果(已产生的结果不会被撤销)
script.outerHTML = ''
delete window[windowKeyName]['EVENT_' + id]
},
// 当js运行出错的时候调用的事件
error(e) {
console.group(`${options.errorMessage || '用户自定义JS增强代码运行出错'}(${new Date()})`)
console.error(e)
console.groupEnd()
}
}
// 将事件挂载到document中
script.innerHTML = code
document.body.appendChild(script)
}
/**
* 重复值验证工具方法
*
* 使用示例:
* { validator: (rule, value, callback) => validateDuplicateValue('sys_fill_rule', 'rule_code', value, this.model.id, callback) }
*
* @param tableName 被验证的表名
* @param fieldName 被验证的字段名
* @param fieldVal 被验证的值
* @param dataId 数据ID,可空
* @param callback
*/
export function validateDuplicateValue(tableName, fieldName, fieldVal, dataId, callback) {
if (fieldVal) {
let params = { tableName, fieldName, fieldVal, dataId }
api.duplicateCheck(params).then(res => {
res['success'] ? callback() : callback(res['message'])
}).catch(err => {
callback(err.message || err)
})
} else {
callback()
}
}
/**
* 根据编码校验规则code,校验传入的值是否合法
*
* 使用示例:
* { validator: (rule, value, callback) => validateCheckRule('common', value, callback) }
*
* @param ruleCode 编码校验规则 code
* @param value 被验证的值
* @param callback
*/
export function validateCheckRule(ruleCode, value, callback) {
if (ruleCode && value) {
value = encodeURIComponent(value)
api.checkRuleByCode({ ruleCode, value }).then(res => {
res['success'] ? callback() : callback(res['message'])
}).catch(err => {
callback(err.message || err)
})
} else {
callback()
}
}
/**
* 如果值不存在就 push 进数组,反之不处理
* @param array 要操作的数据
* @param value 要添加的值
* @param key 可空,如果比较的是对象,可能存在地址不一样但值实际上是一样的情况,可以传此字段判断对象中唯一的字段,例如 id。不传则直接比较实际值
* @returns {boolean} 成功 push 返回 true,不处理返回 false
*/
export function pushIfNotExist(array, value, key) {
for (let item of array) {
if (key && (item[key] === value[key])) {
return false
} else if (item === value) {
return false
}
}
array.push(value)
return true
}
/**
* 可用于判断是否成功
* @type {symbol}
*/
export const succeedSymbol = Symbol()
/**
* 可用于判断是否失败
* @type {symbol}
*/
export const failedSymbol = Symbol()
/**
* 使 promise 无论如何都会 resolve,除非传入的参数不是一个Promise对象或返回Promise对象的方法
* 一般用在 Promise.all 中
*
* @param promise 可传Promise对象或返回Promise对象的方法
* @returns {Promise<any>}
*/
export function alwaysResolve(promise) {
return new Promise((resolve, reject) => {
let p = promise
if (typeof promise === 'function') {
p = promise()
}
if (p instanceof Promise) {
p.then(data => {
resolve({ type: succeedSymbol, data })
}).catch(error => {
resolve({ type: failedSymbol, error })
})
} else {
reject('alwaysResolve: 传入的参数不是一个Promise对象或返回Promise对象的方法')
}
})
}
/**
* 简单实现防抖方法
*
* 防抖(debounce)函数在第一次触发给定的函数时,不立即执行函数,而是给出一个期限值(delay),比如100ms。
* 如果100ms内再次执行函数,就重新开始计时,直到计时结束后再真正执行函数。
* 这样做的好处是如果短时间内大量触发同一事件,只会执行一次函数。
*
* @param fn 要防抖的函数
* @param delay 防抖的毫秒数
* @returns {Function}
*/
export function simpleDebounce(fn, delay = 100) {
let timer = null
return function () {
let args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
/**
* 不用正则的方式替换所有值
* @param text 被替换的字符串
* @param checker 替换前的内容
* @param replacer 替换后的内容
* @returns {String} 替换后的字符串
*/
export function replaceAll(text, checker, replacer) {
let lastText = text
text = text.replace(checker, replacer)
if (lastText !== text) {
return replaceAll(text, checker, replacer)
}
return text
}
/**
* 获取事件冒泡路径,兼容 IE11,Edge,Chrome,Firefox,Safari
* 目前使用的地方:JEditableTable Span模式
*/
export function getEventPath(event) {
let target = event.target
let path = (event.composedPath && event.composedPath()) || event.path
if (path != null) {
return (path.indexOf(window) < 0) ? path.concat(window) : path
}
if (target === window) {
return [window]
}
let getParents = (node, memo) => {
memo = memo || []
const parentNode = node.parentNode
if (!parentNode) {
return memo
} else {
return getParents(parentNode, memo.concat(parentNode))
}
}
return [target].concat(getParents(target), window)
}
/**
* 根据组件名获取父级
* @param vm
* @param name
* @returns {Vue | null|null|Vue}
*/
export function getVmParentByName(vm, name) {
let parent = vm.$parent
if (parent && parent.$options) {
if (parent.$options.name === name) {
return parent
} else {
let res = getVmParentByName(parent, name)
if (res) {
return res
}
}
}
return null
}
/**
* 使一个值永远不会为(null | undefined)
*
* @param value 要处理的值
* @param def 默认值,如果value为(null | undefined)则返回的默认值,可不传,默认为''
*/
export function neverNull(value, def) {
return value == null ? (neverNull(def, '')) : value
}
/**
* 根据元素值移除数组中的一个元素
* @param array 数组
* @param prod 属性名
* @param value 属性值
* @returns {string}
*/
export function removeArrayElement(array, prod, value) {
let index = -1
for(let i = 0;i<array.length;i++){
if(array[i][prod] == value){
index = i;
break;
}
}
if(index>=0){
array.splice(index, 1);
}
}
/** 判断是否是OAuth2APP环境 */
export function isOAuth2AppEnv() {
return /wxwork|dingtalk/i.test(navigator.userAgent)
}
/**
* 获取积木报表打印地址
* @param url
* @param id
* @param open 是否自动打开
* @returns {*}
*/
export function getReportPrintUrl(url, id, open) {
// URL支持{{ window.xxx }}占位符变量
url = url.replace(/{{([^}]+)?}}/g, (s1, s2) => eval(s2))
if (url.includes('?')) {
url += '&'
} else {
url += '?'
}
url += `id=${id}`
url += `&token=${Vue.ls.get(ACCESS_TOKEN)}`
if (open) {
window.open(url)
}
return url
}
/**
* JS实现AOP切面
*
* @param obj 包含函数的对象
* @param funcName 要切面的函数名
* @param callback 执行方法前的回调,用于切面,callback的返回值就是funcName最终的返回值
*/
export function aspectAroundFunction(obj, funcName, callback) {
if (typeof callback !== 'function' || !obj) {
console.warn('【aspectAroundFunction】obj或callback格式不正确')
return
}
// 保存原来的函数
let func = obj[funcName]
if (typeof func !== 'function') {
console.warn('【aspectAroundFunction】' + funcName + '不是一个方法')
return
}
// 赋值新方法
// 实现当外部调用 funcName 时,首先调用我定义的新方法
// 然后调用传入的callback方法,以决定是否执行 funcName,以及更改参数、返回值
obj[funcName] = function (...args) {
return callback({
args,
// 只有执行 proceed 才会真正执行给定的 funcName 方法
proceed() {
try {
return func.apply(obj, args)
} catch (e) {
console.error(e)
}
},
})
}
} |
var backtrack = require('backtrack');
var util = require("util");
// # Depper
// Represents a set of packages that need to be installed
function Depper () {
var self = this;
backtrack.Expression.apply(self);
}
util.inherits(Depper, backtrack.Expression);
// ## pkg
// adds a package to the dependency set
Depper.prototype.pkg = function (/* pkg, versions.. */) {
var self = this;
var args = Array.prototype.slice.apply(arguments);
var name = args.shift();
var versions = args.map(function (item) {
return name + "@" + item;
});
// Install precisely one version of this package
self.xor.apply(self, versions);
};
// ## dep
// Declares source to be `dependent` on `dep`
Depper.prototype.dep = function (source, dep) {
var self = this;
self.or("-" + source, dep);
};
// ## solve
// Solves the dependency set
Depper.prototype.solve = function () {
var self = this;
// Call the original solve method
var results = backtrack.Expression.prototype.solve.apply(self);
// Reduce it into an array of packages that need to be installed
return Object.keys(results).reduce(function (memo, item) {
if (results[item]) memo.push(item);
return memo;
}, []);
};
module.exports = Depper;
|
import React from 'react'
import PropTypes from 'prop-types'
import ScrollAnimation from 'react-animate-on-scroll'
const Video = ({id, preview}) => (
<section className="video wide-section">
<div className="columns">
<div className="column">
<figure className="image is-16by9">
<iframe
className="has-ratio"
id="ytplayer"
type="text/html"
src={`https://www.youtube-nocookie.com/embed/${id}?enablejsapi=1&version=3&playerapiid=ytplayer`}
frameBorder="0"
allowFullScreen>
</iframe>
</figure>
</div>
</div>
</section>
)
Video.propTypes = {
id: PropTypes.string,
preview: PropTypes.bool
}
export default Video |
""""
We consider a simple tidal lagoon - no sluice gate boundaries are included so we only focus on the control of turbines.
This example presents the tidal power plant simulation functionality by coupling operational algorithms with Thetis
boundaries
More information about the tidal range algorithms can be found in:
Angeloudis A, Kramer SC, Avdis A & Piggott MD, Optimising tidal range power plant operation,
Applied Energy,212,680-690, 212, https://doi.org/10.1016/j.apenergy.2017.12.052
"""
from thetis import *
# modules.tools contains the LagoonCallback that is called during the simulation
from modules.tools import *
# input_barrages contains functions to initialise the lagoon status and generic control parameters for the operation
from modules import input_barrages
mesh2d = Mesh('lagoon.msh')
# Initial functions for lagoon
lagoon_input = input_barrages.input_predefined_barrage_specs(turbine_number=25, sluice_number=0, operation='two-way')
t_end = 48 * 3600. # total duration in seconds
t_export = 200.0 # export interval in seconds
Dt = 25 # timestep
if os.getenv('THETIS_REGRESSION_TEST') is not None:
t_end = t_export
# Omega for amplitude of seaward boundary - assumed to be a sinusoidal function with a given amplitude
amplitude = 4.0
period = 12.42 * 3600
omega = (2 * pi) / period
# Bathymetry and viscosity field
P1_2d = get_functionspace(mesh2d, 'DG', 1)
bathymetry_2d = Function(P1_2d, name='Bathymetry')
viscosity_2d = Function(P1_2d, name='viscosity')
# Bathymetry combination of bell curve and sloping bathymetry
x, y = SpatialCoordinate(mesh2d)
depth_oce = 20.0
depth_riv = -10.0
mi, sigma = 0, 2000
bathymetry_2d.interpolate(-2 * 1e5 * (-1 / (sigma * sqrt(2 * pi)) * exp(-(y - 3000 - mi)**2 / (2 * sigma**2)))
+ (depth_riv - depth_oce) * x/16e3)
# Viscosity sponge at the seaward boundary
viscosity_2d.interpolate(conditional(le(x, 2e3), 1e3 * (2e3+1 - x)/2e3, 1))
# create solver
solver_obj = solver2d.FlowSolver2d(mesh2d, bathymetry_2d)
options = solver_obj.options
options.simulation_export_time = t_export
options.simulation_end_time = t_end
options.check_volume_conservation_2d = True
options.swe_timestepper_type = 'CrankNicolson'
options.fields_to_export = ['uv_2d', 'elev_2d']
options.swe_timestepper_options.implicitness_theta = 0.5
options.swe_timestepper_options.use_semi_implicit_linearization = True
options.use_wetting_and_drying = True
options.wetting_and_drying_alpha = Constant(0.5)
options.manning_drag_coefficient = Constant(0.02)
options.horizontal_viscosity = viscosity_2d
options.timestep = Dt
# set initial condition for elevation, piecewise linear function
elev_init = Function(P1_2d)
elev_init.assign(0.0)
tidal_elev = Function(bathymetry_2d.function_space())
# Initialise hydraulic structure boundaries and max them as fluxes
lagoon_hydraulic_structures = {"sl_i": Constant(0.), "sl_o": Constant(0.), "tb_i": Constant(0.), "tb_o": Constant(0.)}
solver_obj.bnd_functions['shallow_water'] = {5: {'elev': tidal_elev},
2: {'flux': lagoon_hydraulic_structures["tb_i"]},
1: {'flux': lagoon_hydraulic_structures["tb_o"]}, }
solver_obj.assign_initial_conditions(uv=as_vector((1e-5, 0.0)), elev=elev_init)
# Create tidal lagoon callback
# dx(1) is outer location, dx(2) is inner location (marked areas using gmsh)
cb_lagoon = LagoonCallback(solver_obj, {"inner": dx(2), "outer": dx(1)}, lagoon_input,
thetis_boundaries=lagoon_hydraulic_structures,
number_timesteps=5, name="lagoon_1", export_to_hdf5=True)
solver_obj.add_callback(cb_lagoon, 'timestep')
def update_forcings(t_new,):
tidal_elev.assign(Constant(tanh((t_new)/(4*3600.)) * amplitude * sin(omega * t_new)))
# Solve the system
solver_obj.iterate(update_forcings=update_forcings)
|
window.onload = function() {
setVariable();
};
function setVariable() {
hljs.highlightAll();
} |
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Reminds', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
category: {
allowNull: true,
type: Sequelize.STRING
},
title: {
allowNull: true,
type: Sequelize.STRING
},
notes: {
allowNull: true,
type: Sequelize.STRING
},
dateOfRemind: {
allowNull: true,
type: Sequelize.DATE
},
type: {
allowNull: true,
type: Sequelize.STRING
},
urgency: {
allowNull: true,
type: Sequelize.STRING
},
expired: {
allowNull: true,
type: Sequelize.BOOLEAN,
defaultValue: false
},
//UserId: {
// type: Sequelize.UUID,
// references: {
// model: {
// tableName: 'Users',
// schema: 'smart_remind_schema'
// },
// key: 'id'
// },
// allowNull: true
//},
//GroupId: {
// type: Sequelize.UUID,
// references: {
// model: {
// tableName: 'Groups',
// schema: 'smart_remind_schema'
// },
// key: 'id'
// },
// allowNull: true
//},
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Reminds');
}
};
|
import {action} from '@enact/storybook-utils/addons/actions';
import {boolean, select, text} from '@enact/storybook-utils/addons/controls';
import Button from '@enact/lune/Button';
import {Header} from '@enact/lune/Panels';
import Picker from '@enact/lune/Picker';
import PopupTabLayout, {Tab, TabPanels, TabPanel} from '@enact/lune/PopupTabLayout';
import Scroller from '@enact/lune/Scroller';
import {Row} from '@enact/ui/Layout';
import {Component} from 'react';
import iconNames from '../helper/icons';
import Section from './components/KitchenSinkSection';
import PickerAddRemove from './components/PickerAddRemove';
import PickerRTL from './components/PickerRTL';
import css from './Picker.module.less';
Picker.displayName = 'Picker';
const prop = {
orientation: ['horizontal', 'vertical'],
width: [null, 'small', 'medium', 'large']
};
const pickerList = {
tall: ['नरेंद्र मोदी', ' ฟิ้ ไั ஒ து', 'ÃÑÕÂÊÎÔÛÄËÏÖÜŸ', 'តន្ត្រី'],
long: [
'1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Varius sit amet mattis vulputate enim nulla. A pellentesque sit amet porttitor eget dolor morbi non arcu. Text1',
'2 Sit amet consectetur adipiscing elit. Ac turpis egestas integer eget aliquet nibh. Est ullamcorper eget nulla facilisi etiam dignissim. Pellentesque dignissim enim sit amet. Non blandit massa enim nec dui nunc mattis. Text2',
'3 Platea dictumst vestibulum rhoncus est pellentesque. Massa sapien faucibus et molestie ac feugiat. Diam quis enim lobortis scelerisque fermentum dui faucibus. Urna nec tincidunt praesent semper feugiat nibh sed pulvinar. Text3',
'4 In metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Urna id volutpat lacus laoreet non curabitur. Lobortis feugiat vivamus at augue. Praesent semper feugiat nibh sed. Ac tincidunt vitae semper quis lectus. Text4',
'5 Purus sit amet volutpat consequat mauris nunc congue nisi. Sit amet cursus sit amet dictum sit amet justo. Imperdiet massa tincidunt nunc pulvinar sapien et ligula ullamcorper. Libero id faucibus nisl tincidunt eget. Text5'
],
vegetables: ['Celery', 'Carrot', 'Tomato', 'Onion', 'Broccoli', 'Spinach'],
longVegetables: [
'Celery contains potassium',
'Carrot contains beta carotene',
'Tomatoes contain folate',
'Onion contains calcium',
'Broccoli contains iron',
'Spinach contains manganese'
],
numberList: ['0', '1', '2', '3', '4'],
irregularNumberList: ['4', '13', '15', '20', '22'],
oneAirport: ['San Francisco International Airport Terminal 1'],
emptyList: [],
orderedList: ['A', 'B', 'C', 'D', 'E', 'F'],
airports: [
'San Francisco International Airport Terminal 1',
'Milan Malpensa Airport Terminal 2',
'Paris-Charles De Gaulle Airport Terminal 3',
'Boston Logan Airport Terminal D',
'Tokyo Narita Airport Terminal 5',
'Heathrow Terminal 6',
'נמל התעופה בן גוריון טרמינל הבינלאומי'
]
};
class PickerInPopupTabLayout extends Component {
render () {
return (
<>
<PopupTabLayout open index={0}>
<Tab title="Display">
<TabPanels>
<TabPanel>
<Header title="Display 0" type="compact">
<slotAfter>
<Button>hello</Button>
</slotAfter>
</Header>
<div>
<Picker
onChange={action('onChange')}
width={select('width', prop.width, Picker, 'small')}
orientation={select('orientation', prop.orientation, Picker, 'horizontal')}
wrap={boolean('wrap', Picker)}
joined={boolean('joined', Picker)}
noAnimation={boolean('noAnimation', Picker)}
disabled={boolean('disabled', Picker)}
incrementIcon={select('incrementIcon', iconNames, Picker)}
decrementIcon={select('decrementIcon', iconNames, Picker)}
>
{pickerList.vegetables}
</Picker>
</div>
</TabPanel>
</TabPanels>
</Tab>
</PopupTabLayout>
</>
);
}
}
export default {
title: 'Lune/Picker',
component: 'Picker'
};
export const WithLongText = (args) => (
<Picker
onChange={action('onChange')}
width={args['width']}
orientation={args['orientation']}
wrap={args['wrap']}
joined={args['joined']}
noAnimation={args['noAnimation']}
disabled={args['disabled']}
incrementIcon={args['incrementIcon']}
decrementIcon={args['decrementIcon']}
>
{pickerList.long}
</Picker>
);
select('width', WithLongText, prop.width, Picker, 'large');
select('orientation', WithLongText, prop.orientation, Picker, 'horizontal');
boolean('wrap', WithLongText, Picker);
boolean('joined', WithLongText, Picker);
boolean('noAnimation', WithLongText, Picker);
boolean('disabled', WithLongText, Picker);
select('incrementIcon', WithLongText, iconNames, Picker);
select('decrementIcon', WithLongText, iconNames, Picker);
WithLongText.storyName = 'with long text';
export const WithTallCharacters = (args) => (
<Picker
onChange={action('onChange')}
width={args['width']}
orientation={args['orientation']}
wrap={args['wrap']}
joined={args['joined']}
noAnimation={args['noAnimation']}
disabled={args['disabled']}
incrementIcon={args['incrementIcon']}
decrementIcon={args['decrementIcon']}
>
{pickerList.tall}
</Picker>
);
select('width', WithTallCharacters, prop.width, Picker, 'large');
select('orientation', WithTallCharacters, prop.orientation, Picker, 'horizontal');
boolean('wrap', WithTallCharacters, Picker);
boolean('joined', WithTallCharacters, Picker);
boolean('noAnimation', WithTallCharacters, Picker);
boolean('disabled', WithTallCharacters, Picker);
select('incrementIcon', WithTallCharacters, iconNames, Picker);
select('decrementIcon', WithTallCharacters, iconNames, Picker);
WithTallCharacters.storyName = 'with tall characters';
export const WithADefaultValue = (args) => (
<Picker
onChange={action('onChange')}
width={args['width']}
orientation={args['orientation']}
wrap={args['wrap']}
joined={args['joined']}
noAnimation={args['noAnimation']}
disabled={args['disabled']}
incrementIcon={args['incrementIcon']}
decrementIcon={args['decrementIcon']}
defaultValue={2}
>
{pickerList.longVegetables}
</Picker>
);
select('width', WithADefaultValue, prop.width, Picker, 'medium');
select('orientation', WithADefaultValue, prop.orientation, Picker, 'horizontal');
boolean('wrap', WithADefaultValue, Picker);
boolean('joined', WithADefaultValue, Picker);
boolean('noAnimation', WithADefaultValue, Picker);
boolean('disabled', WithADefaultValue, Picker);
select('incrementIcon', WithADefaultValue, iconNames, Picker);
select('decrementIcon', WithADefaultValue, iconNames, Picker);
WithADefaultValue.storyName = 'with a default value';
export const WithNoItemsPlat30963 = (args) => (
<Picker
onChange={action('onChange')}
width={args['width']}
orientation={args['orientation']}
wrap={args['wrap']}
joined={args['joined']}
noAnimation={args['noAnimation']}
disabled={args['disabled']}
incrementIcon={args['incrementIcon']}
decrementIcon={args['decrementIcon']}
>
{[]}
</Picker>
);
select('width', WithNoItemsPlat30963, prop.width, Picker, 'large');
select('orientation', WithNoItemsPlat30963, prop.orientation, Picker, 'horizontal');
boolean('wrap', WithNoItemsPlat30963, Picker, true);
boolean('joined', WithNoItemsPlat30963, Picker);
boolean('noAnimation', WithNoItemsPlat30963, Picker);
boolean('disabled', WithNoItemsPlat30963, Picker);
select('incrementIcon', WithNoItemsPlat30963, iconNames, Picker);
select('decrementIcon', WithNoItemsPlat30963, iconNames, Picker);
WithNoItemsPlat30963.storyName = 'with no items (PLAT-30963)';
export const WithOneItem = (args) => (
<Picker
onChange={action('onChange')}
width={args['width']}
orientation={args['orientation']}
wrap={args['wrap']}
joined={args['joined']}
noAnimation={args['noAnimation']}
disabled={args['disabled']}
incrementIcon={args['incrementIcon']}
decrementIcon={args['decrementIcon']}
>
{pickerList.oneAirport}
</Picker>
);
select('width', WithOneItem, prop.width, Picker, 'large');
select('orientation', WithOneItem, prop.orientation, Picker, 'horizontal');
boolean('wrap', WithOneItem, Picker, true);
boolean('joined', WithOneItem, Picker);
boolean('noAnimation', WithOneItem, Picker);
boolean('disabled', WithOneItem, Picker);
select('incrementIcon', WithOneItem, iconNames, Picker);
select('decrementIcon', WithOneItem, iconNames, Picker);
WithOneItem.storyName = 'with one item';
export const WithItemAddRemoveEnyo2448 = (args) => (
<PickerAddRemove
width={args['width']}
orientation={args['orientation']}
wrap={args['wrap']}
joined={args['joined']}
noAnimation={args['noAnimation']}
disabled={args['disabled']}
>
{pickerList.emptyList}
</PickerAddRemove>
);
select('width', WithItemAddRemoveEnyo2448, prop.width, Picker, 'medium');
select('orientation', WithItemAddRemoveEnyo2448, prop.orientation, Picker, 'horizontal');
boolean('wrap', WithItemAddRemoveEnyo2448, Picker, true);
boolean('joined', WithItemAddRemoveEnyo2448, Picker);
boolean('noAnimation', WithItemAddRemoveEnyo2448, Picker);
boolean('disabled', WithItemAddRemoveEnyo2448, Picker);
WithItemAddRemoveEnyo2448.storyName = 'with item add/remove (ENYO-2448)';
export const RtlLayoutPlat28123 = (args) => (
<PickerRTL
width={args['width']}
wrap={args['wrap']}
joined={args['joined']}
noAnimation={args['noAnimation']}
disabled={args['disabled']}
>
{pickerList.orderedList}
</PickerRTL>
);
select('width', RtlLayoutPlat28123, prop.width, Picker, 'medium');
boolean('wrap', RtlLayoutPlat28123, Picker, true);
boolean('joined', RtlLayoutPlat28123, Picker);
boolean('noAnimation', RtlLayoutPlat28123, Picker);
boolean('disabled', RtlLayoutPlat28123, Picker);
RtlLayoutPlat28123.storyName = 'RTL Layout (PLAT-28123)';
export const KitchenSink = () => (
<Scroller>
<Row wrap>
<Section title="Horizontal" size="100%">
<Picker alt="Basic" width="medium">
{pickerList.vegetables}
</Picker>
<Picker alt="Disabled" width="medium" disabled>
{pickerList.vegetables}
</Picker>
<Picker alt="Tall text" width="medium">
{pickerList.tall}
</Picker>
<Picker alt="No Width">{pickerList.vegetables}</Picker>
<Picker alt="Small" width="small">
{pickerList.orderedList}
</Picker>
<Picker alt="Medium" width="medium">
{pickerList.vegetables}
</Picker>
<Picker alt="Large" width="large">
{pickerList.airports}
</Picker>
<Picker alt="Width=1" width={1}>
{pickerList.numberList}
</Picker>
<Picker alt="Width=5" width={5}>
{pickerList.orderedList}
</Picker>
<Picker alt="Width=10" width={10}>
{pickerList.vegetables}
</Picker>
<Picker alt="Width=20" width={20}>
{pickerList.airports}
</Picker>
</Section>
<Section title="Vertical" size="100%">
<Picker orientation="vertical" alt="Basic" width="medium">
{pickerList.vegetables}
</Picker>
<Picker orientation="vertical" alt="Disabled" width="medium" disabled>
{pickerList.vegetables}
</Picker>
<Picker orientation="vertical" alt="Tall text" width="medium">
{pickerList.tall}
</Picker>
<Picker orientation="vertical" alt="No Width">
{pickerList.vegetables}
</Picker>
<Picker orientation="vertical" alt="Small" width="small">
{pickerList.orderedList}
</Picker>
<Picker orientation="vertical" alt="Medium" width="medium">
{pickerList.vegetables}
</Picker>
<Picker orientation="vertical" alt="Large" width="large">
{pickerList.airports}
</Picker>
<Picker orientation="vertical" alt="Width=1" width={1}>
{pickerList.numberList}
</Picker>
<Picker orientation="vertical" alt="Width=5" width={5}>
{pickerList.orderedList}
</Picker>
<Picker orientation="vertical" alt="Width=10" width={10}>
{pickerList.vegetables}
</Picker>
<Picker orientation="vertical" alt="Width=20" width={20}>
{pickerList.airports}
</Picker>
</Section>
<Section title="Joined Horizontal" size="100%">
<Picker joined alt="Basic" width="medium">
{pickerList.vegetables}
</Picker>
<Picker joined alt="Disabled" width="medium" disabled>
{pickerList.vegetables}
</Picker>
<Picker joined alt="Tall text" width="medium">
{pickerList.tall}
</Picker>
<Picker joined alt="No Width">
{pickerList.vegetables}
</Picker>
<Picker joined alt="Small" width="small">
{pickerList.orderedList}
</Picker>
<Picker joined alt="Medium" width="medium">
{pickerList.vegetables}
</Picker>
<Picker joined alt="Large" width="large">
{pickerList.airports}
</Picker>
<Picker joined alt="Width=1" width={1}>
{pickerList.numberList}
</Picker>
<Picker joined alt="Width=5" width={5}>
{pickerList.orderedList}
</Picker>
<Picker joined alt="Width=10" width={10}>
{pickerList.vegetables}
</Picker>
<Picker joined alt="Width=20" width={20}>
{pickerList.airports}
</Picker>
</Section>
<Section title="Joined Vertical" size="100%">
<Picker joined orientation="vertical" alt="Basic" width="medium">
{pickerList.vegetables}
</Picker>
<Picker joined orientation="vertical" alt="Disabled" width="medium" disabled>
{pickerList.vegetables}
</Picker>
<Picker joined orientation="vertical" alt="Tall text" width="medium">
{pickerList.tall}
</Picker>
<Picker joined orientation="vertical" alt="No Width">
{pickerList.vegetables}
</Picker>
<Picker joined orientation="vertical" alt="Small" width="small">
{pickerList.orderedList}
</Picker>
<Picker joined orientation="vertical" alt="Medium" width="medium">
{pickerList.vegetables}
</Picker>
<Picker joined orientation="vertical" alt="Large" width="large">
{pickerList.airports}
</Picker>
<Picker joined orientation="vertical" alt="Width=1" width={1}>
{pickerList.numberList}
</Picker>
<Picker joined orientation="vertical" alt="Width=5" width={5}>
{pickerList.orderedList}
</Picker>
<Picker joined orientation="vertical" alt="Width=10" width={10}>
{pickerList.vegetables}
</Picker>
<Picker joined orientation="vertical" alt="Width=20" width={20}>
{pickerList.airports}
</Picker>
</Section>
</Row>
</Scroller>
);
KitchenSink.parameters = {
controls: {
hideNoControlsWarning: true
}
};
export const ForIrregularNumbers = (args) => (
<Picker
joined={args['joined']}
orientation={args['orientation']}
reverse={false}
type="number"
>
{pickerList.irregularNumberList}
</Picker>
);
boolean('joined', ForIrregularNumbers, Picker);
select('orientation', ForIrregularNumbers, prop.orientation, Picker);
ForIrregularNumbers.storyName = 'for irregular numbers';
export const InPopupTabLayout = () => <PickerInPopupTabLayout />;
InPopupTabLayout.storyName = 'in PopupTabLayout';
InPopupTabLayout.parameters = {
controls: {
hideNoControlsWarning: true
}
};
export const WithCustomizedTitleStyle = (args) => (
<Picker
aria-label={args['aria-label']}
css={css}
disabled={args['disabled']}
inlineTitle={args['inlineTitle']}
joined={args['joined']}
noAnimation={args['noAnimation']}
onChange={action('onChange')}
title={args['title']}
width={args['width']}
wrap={args['wrap']}
>
{pickerList.airports}
</Picker>
);
text('aria-label', WithCustomizedTitleStyle, Picker, '');
boolean('disabled', WithCustomizedTitleStyle, Picker);
boolean('inlineTitle', WithCustomizedTitleStyle, Picker);
boolean('joined', WithCustomizedTitleStyle, Picker);
boolean('noAnimation', WithCustomizedTitleStyle, Picker);
text('title', WithCustomizedTitleStyle, Picker, 'Long title with customized style');
select('width', WithCustomizedTitleStyle, prop.width, Picker, 'large');
boolean('wrap', WithCustomizedTitleStyle, Picker);
WithCustomizedTitleStyle.storyName = 'With Customized Style';
|
import axios from 'axios'
export const getCarro = async () => {
axios.get("http://apiadvisor.climatempo.com.br/api/v1/climate/temperature/locale/3477?token=your-app-token")
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
} |
var fs = require('fs');
var XmlStream = require('xml-stream');
var stream = fs.createReadStream('wiki.xml');
var xml = new XmlStream(stream);
// returns a unique array
function uniq(a) {
var seen = {};
return a.filter(function(item) {
return seen.hasOwnProperty(item) ? false : (seen[item] = true);
});
}
var possibles = {
'===Noun===': -1,
'===Verb===': -1,
'===Adverb===': -1,
'===Adjective===': -1,
'===Preposition===': -1,
'===Numeral===': -1,
'===Proper noun===': -1,
'===Pronoun===': -1,
'===Particle===': -1,
'===Interjection===': -1,
'===Determiner===': -1,
'===Phrase===': -1,
'===Contraction===': -1,
'===Conjunction===': -1,
'===Article===': -1,
'===Suffix===': -1,
'===Initialism===': -1,
'===Proverb===': -1,
'===Number===': -1,
'===Abbreviation===' : -1,
'===Prefix===': -1,
'===Prepositional phrase===': -1
}
function getMatches(string, regex, index, title) {
index || (index = 1); // default to the first capturing group
var matches = {
word: title.toLowerCase(),
translations: {}
};
var match;
var finaz = '';
var tmp = 10000000;
// this shows some words that fails to find translations
// if(!regex.exec(string)) {
// console.log(title);
// }
while (match = regex.exec(string)) {
tmp = 10000000;
for (key in possibles) {
var pos = match.input.indexOf(key);
if (pos == -1) {
} else {
// existe um tipo de traducao
var diff = match.index - pos;
if(diff > 0 && diff < tmp) {
tmp = diff;
finaz = key;
}
}
}
var pos = finaz.replace('===', '').replace('===', '').toLowerCase();
if(matches.translations[pos]) {
pushe = match[1].replace(/(\[\[|\]\])/g, '');
matches.translations[pos].push(pushe);
matches.translations[pos] = uniq(matches.translations[pos]);
} else {
pushe = match[1].replace(/(\[\[|\]\])/g, '');
matches.translations[pos] = [pushe];
};
}
//console.log(matches.word);
return matches;
}
// check if there are portuguese translations of the word
// new regex -> (t|t\+)\|pt\|(.*?)(\||\})
// old -> /\|pt\|(.*?)(\||\})/g
var trans_exp = /t\+\|pt\|(.*?)(\||\})/g;
// check if the word has audio
var audio_exp = /\{\{audio\|(.*?-us-.*?)\|Audio \(US\)/g;
var count = 0;
xml.on('endElement: page', function(item) {
var str = item['revision']['text']['$text'];
if (str != null && str.indexOf('==English==') != -1) {
if (item['title'].indexOf(":") == -1) {
//console.log(item['title']);
var word = getMatches(str, trans_exp, 1, item['title']);
var match = audio_exp.exec(str);
try {
var len = match[1].split("|");
var audios = len.filter(function (item) {
return item.indexOf('-us-') >= 0;
})
if (audios.length > 1) {
sound = audios[1];
} else if (audios.length == 1) {
sound= audios[0];
}
word.sound = sound;
} catch (err) {
word.sound = null;
}
}
if(word !== undefined && Object.keys(word.translations).length > 0) {
console.log(JSON.stringify(word));
}
};
});
function checkEmptyKeys(word) {
if(word && Object.keys(word.translations).length) {
if(word.translations['']) {
console.log(word);
}
}
}
function doTest (word) {
var test_array = [
'me',
'for',
'know',
'time',
'game',
'know',
'data',
'time',
'an',
'library',
'the',
'change',
'as',
'jesus',
'november'
]
if(word && test_array.includes(word.word)) {
console.log(JSON.stringify(word));
}
}
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(searchElement, fromIndex) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
// c. Increase k by 1.
// NOTE: === provides the correct "SameValueZero" comparison needed here.
if (o[k] === searchElement) {
return true;
}
k++;
}
// 8. Return false
return false;
}
});
} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = faviconTagsBuilder;
var _buildFileUrl = _interopRequireDefault(require("./buildFileUrl"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var tag = function tag(tagName, attributes) {
return {
tagName: tagName,
attributes: attributes
};
};
var metaTag = function metaTag(name, content) {
return tag('meta', {
name: name,
content: content
});
};
var url = function url(favicon, entitiesRepo, params) {
var upload = entitiesRepo.findEntity('upload', favicon);
return (0, _buildFileUrl["default"])(upload, entitiesRepo, params);
};
var builders = {
apple: function apple(entitiesRepo) {
var site = entitiesRepo.site;
if (!site.favicon) return undefined;
return [57, 60, 72, 76, 114, 120, 144, 152, 180].map(function (size) {
return tag('link', {
rel: 'apple-touch-icon',
sizes: "".concat(size, "x").concat(size),
href: url(site.favicon, entitiesRepo, {
w: size,
h: size
})
});
});
},
windows: function windows(entitiesRepo) {
var site = entitiesRepo.site;
if (!site.favicon) return undefined;
return [[70, 70], [150, 150], [310, 310], [310, 150]].map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
w = _ref2[0],
h = _ref2[1];
return metaTag("msapplication-square".concat(w, "x").concat(h), url(site.favicon, entitiesRepo, {
w: w,
h: h
}));
});
},
icon: function icon(entitiesRepo) {
var site = entitiesRepo.site;
if (!site.favicon) return undefined;
var upload = entitiesRepo.findEntity('upload', site.favicon);
if (!upload) return undefined;
return [16, 32, 96, 192].map(function (size) {
return tag('link', {
rel: 'icon',
sizes: "".concat(size, "x").concat(size),
href: url(site.favicon, entitiesRepo, {
w: size,
h: size
}),
type: "image/".concat(upload.format)
});
});
},
appName: function appName(entitiesRepo) {
var site = entitiesRepo.site;
if (!site.name) return undefined;
return metaTag('application-name', site.name);
}
};
function faviconTagsBuilder(entitiesRepo) {
return Object.values(builders).reduce(function (acc, builder) {
var result = builder(entitiesRepo);
if (result) {
if (Array.isArray(result)) {
return [].concat(acc, result);
}
return [].concat(acc, [result]);
}
return acc;
}, []);
} |
day_of_week = input()
work_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
vacation_days = ['Saturday', 'Sunday']
if day_of_week in (work_days):
print('Working day')
elif day_of_week in (vacation_days):
print('Weekend')
else:
print('Error') |
import mapboxgl from 'mapbox-gl-js-mock';
import { interactions } from '../../src/constants';
export default function createMap(mapOptions = {}) {
const map = new mapboxgl.Map(Object.assign({
container: document.createElement('div'),
style: 'mapbox://styles/mapbox/streets-v8'
}, mapOptions));
// Some mock project/unproject functions
map.project = ([y, x]) => ({ x, y });
map.unproject = ([x, y]) => ({ lng: y, lat: x });
if (mapOptions.container) {
map.getContainer = () => mapOptions.container;
}
// Mock up the interaction functions
interactions.forEach((interaction) => {
map[interaction] = {
enabled: true,
disable: function () { this.enabled = false; },
enable: function () { this.enabled = true; },
isEnabled: function () { return this.enabled; },
};
});
map.getCanvas = function() {
return map.getContainer();
};
let classList = [];
const container = map.getContainer();
container.classList.add = function(names) {
names = names || '';
names.split(' ').forEach(name => {
if (classList.indexOf(name) === -1) {
classList.push(name);
}
});
container.className = classList.join(' ');
};
container.classList.remove = function(names) {
names = names || '';
names.split(' ').forEach(name => {
classList = classList.filter(n => n !== name);
});
container.className = classList.join(' ');
};
container.className = classList.join(' ');
container.getBoundingClientRect = function() {
return {
left: 0,
top: 0
};
};
map.getContainer = function() {
return container;
};
return map;
}
|
var searchData=
[
['threaddata',['ThreadData',['../structThreadData.html',1,'']]],
['timer',['Timer',['../structTimer.html',1,'']]],
['tlsconnectparams',['TLSConnectParams',['../structTLSConnectParams.html',1,'']]],
['tobereceivedackrecord_5ft',['ToBeReceivedAckRecord_t',['../structToBeReceivedAckRecord__t.html',1,'']]]
];
|
/*!
* paths 3.1.1
* https://greensock.com
*
* Copyright 2008-2020, GreenSock. All rights reserved.
* Subject to the terms at https://greensock.com/standard-license or for
* Club GreenSock members, the agreement issued with that membership.
* @author: Jack Doyle, [email protected]
*/
/* eslint-disable */
let _svgPathExp = /[achlmqstvz]|(-?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,
_numbersExp = /(?:(-)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,
_scientific = /[\+\-]?\d*\.?\d+e[\+\-]?\d+/ig,
_selectorExp = /(^[#\.][a-z]|[a-y][a-z])/i,
_DEG2RAD = Math.PI / 180,
_RAD2DEG = 180 / Math.PI,
_sin = Math.sin,
_cos = Math.cos,
_abs = Math.abs,
_sqrt = Math.sqrt,
_atan2 = Math.atan2,
_largeNum = 1e8,
_isString = value => typeof(value) === "string",
_isNumber = value => typeof(value) === "number",
_isUndefined = value => typeof(value) === "undefined",
_temp = {},
_temp2 = {},
_roundingNum = 1e5,
_wrapProgress = progress => (Math.round((progress + _largeNum) % 1 * _roundingNum) / _roundingNum) || ((progress < 0) ? 0 : 1), //if progress lands on 1, the % will make it 0 which is why we || 1, but not if it's negative because it makes more sense for motion to end at 0 in that case.
_round = value => ~~(value * _roundingNum + (value < 0 ? -.5 : .5)) / _roundingNum,
_splitSegment = (rawPath, segIndex, i, t) => {
let segment = rawPath[segIndex],
shift = t === 1 ? 6 : subdivideSegment(segment, i, t);
if (shift && shift + i + 2 < segment.length) {
rawPath.splice(segIndex, 0, segment.slice(0, i + shift + 2));
segment.splice(0, i + shift);
return 1;
}
},
_reverseRawPath = (rawPath, skipOuter) => {
let i = rawPath.length;
if (!skipOuter) {
rawPath.reverse();
}
while (i--) {
if (!rawPath[i].reversed) {
reverseSegment(rawPath[i]);
}
}
},
_copyMetaData = (source, copy) => {
copy.totalLength = source.totalLength;
if (source.samples) { //segment
copy.samples = source.samples.slice(0);
copy.lookup = source.lookup.slice(0);
copy.minLength = source.minLength;
copy.resolution = source.resolution;
} else { //rawPath
copy.totalPoints = source.totalPoints;
}
return copy;
},
//pushes a new segment into a rawPath, but if its starting values match the ending values of the last segment, it'll merge it into that same segment (to reduce the number of segments)
_appendOrMerge = (rawPath, segment) => {
let index = rawPath.length,
prevSeg = rawPath[index - 1] || [],
l = prevSeg.length;
if (segment[0] === prevSeg[l-2] && segment[1] === prevSeg[l-1]) {
segment = prevSeg.concat(segment.slice(2));
index--;
}
rawPath[index] = segment;
},
_bestDistance;
/* TERMINOLOGY
- RawPath - an array of arrays, one for each Segment. A single RawPath could have multiple "M" commands, defining Segments (paths aren't always connected).
- Segment - an array containing a sequence of Cubic Bezier coordinates in alternating x, y, x, y format. Starting anchor, then control point 1, control point 2, and ending anchor, then the next control point 1, control point 2, anchor, etc. Uses less memory than an array with a bunch of {x, y} points.
- Bezier - a single cubic Bezier with a starting anchor, two control points, and an ending anchor.
- the variable "t" is typically the position along an individual Bezier path (time) and it's NOT linear, meaning it could accelerate/decelerate based on the control points whereas the "p" or "progress" value is linearly mapped to the whole path, so it shouldn't really accelerate/decelerate based on control points. So a progress of 0.2 would be almost exactly 20% along the path. "t" is ONLY in an individual Bezier piece.
*/
//accepts basic selector text, a path instance, a RawPath instance, or a Segment and returns a RawPath (makes it easy to homogenize things). If an element or selector text is passed in, it'll also cache the value so that if it's queried again, it'll just take the path data from there instead of parsing it all over again (as long as the path data itself hasn't changed - it'll check).
export function getRawPath(value) {
value = (_isString(value) && _selectorExp.test(value)) ? document.querySelector(value) || value : value;
let e = value.getAttribute ? value : 0,
rawPath;
if (e && (value = value.getAttribute("d"))) {
//implements caching
if (!e._gsPath) {
e._gsPath = {};
}
rawPath = e._gsPath[value];
return (rawPath && !rawPath._dirty) ? rawPath : (e._gsPath[value] = stringToRawPath(value));
}
return !value ? console.warn("Expecting a <path> element or an SVG path data string") : _isString(value) ? stringToRawPath(value) : (_isNumber(value[0])) ? [value] : value;
}
//copies a RawPath WITHOUT the length meta data (for speed)
export function copyRawPath(rawPath) {
let a = [],
i = 0;
for (; i < rawPath.length; i++) {
a[i] = _copyMetaData(rawPath[i], rawPath[i].slice(0));
}
return _copyMetaData(rawPath, a);
}
export function reverseSegment(segment) {
let i = 0,
y;
segment.reverse(); //this will invert the order y, x, y, x so we must flip it back.
for (; i < segment.length; i += 2) {
y = segment[i];
segment[i] = segment[i+1];
segment[i+1] = y;
}
segment.reversed = !segment.reversed;
}
let _createPath = (e, ignore) => {
let path = document.createElementNS("http://www.w3.org/2000/svg", "path"),
attr = [].slice.call(e.attributes),
i = attr.length,
name;
ignore = "," + ignore + ",";
while (--i > -1) {
name = attr[i].nodeName.toLowerCase(); //in Microsoft Edge, if you don't set the attribute with a lowercase name, it doesn't render correctly! Super weird.
if (ignore.indexOf("," + name + ",") < 0) {
path.setAttributeNS(null, name, attr[i].nodeValue);
}
}
return path;
},
_typeAttrs = {
rect:"rx,ry,x,y,width,height",
circle:"r,cx,cy",
ellipse:"rx,ry,cx,cy",
line:"x1,x2,y1,y2"
},
_attrToObj = (e, attrs) => {
let props = attrs ? attrs.split(",") : [],
obj = {},
i = props.length;
while (--i > -1) {
obj[props[i]] = +e.getAttribute(props[i]) || 0;
}
return obj;
};
//converts an SVG shape like <circle>, <rect>, <polygon>, <polyline>, <ellipse>, etc. to a <path>, swapping it in and copying the attributes to match.
export function convertToPath(element, swap) {
let type = element.tagName.toLowerCase(),
circ = 0.552284749831,
data, x, y, r, ry, path, rcirc, rycirc, points, w, h, x2, x3, x4, x5, x6, y2, y3, y4, y5, y6, attr;
if (type === "path" || !element.getBBox) {
return element;
}
path = _createPath(element, "x,y,width,height,cx,cy,rx,ry,r,x1,x2,y1,y2,points");
attr = _attrToObj(element, _typeAttrs[type]);
if (type === "rect") {
r = attr.rx;
ry = attr.ry;
x = attr.x;
y = attr.y;
w = attr.width - r * 2;
h = attr.height - ry * 2;
if (r || ry) { //if there are rounded corners, render cubic beziers
x2 = x + r * (1 - circ);
x3 = x + r;
x4 = x3 + w;
x5 = x4 + r * circ;
x6 = x4 + r;
y2 = y + ry * (1 - circ);
y3 = y + ry;
y4 = y3 + h;
y5 = y4 + ry * circ;
y6 = y4 + ry;
data = "M" + x6 + "," + y3 + " V" + y4 + " C" + [x6, y5, x5, y6, x4, y6, x4 - (x4 - x3) / 3, y6, x3 + (x4 - x3) / 3, y6, x3, y6, x2, y6, x, y5, x, y4, x, y4 - (y4 - y3) / 3, x, y3 + (y4 - y3) / 3, x, y3, x, y2, x2, y, x3, y, x3 + (x4 - x3) / 3, y, x4 - (x4 - x3) / 3, y, x4, y, x5, y, x6, y2, x6, y3].join(",") + "z";
} else {
data = "M" + (x + w) + "," + y + " v" + h + " h" + (-w) + " v" + (-h) + " h" + w + "z";
}
} else if (type === "circle" || type === "ellipse") {
if (type === "circle") {
r = ry = attr.r;
rycirc = r * circ;
} else {
r = attr.rx;
ry = attr.ry;
rycirc = ry * circ;
}
x = attr.cx;
y = attr.cy;
rcirc = r * circ;
data = "M" + (x+r) + "," + y + " C" + [x+r, y + rycirc, x + rcirc, y + ry, x, y + ry, x - rcirc, y + ry, x - r, y + rycirc, x - r, y, x - r, y - rycirc, x - rcirc, y - ry, x, y - ry, x + rcirc, y - ry, x + r, y - rycirc, x + r, y].join(",") + "z";
} else if (type === "line") {
data = "M" + attr.x1 + "," + attr.y1 + " L" + attr.x2 + "," + attr.y2; //previously, we just converted to "Mx,y Lx,y" but Safari has bugs that cause that not to render properly when using a stroke-dasharray that's not fully visible! Using a cubic bezier fixes that issue.
} else if (type === "polyline" || type === "polygon") {
points = (element.getAttribute("points") + "").match(_numbersExp) || [];
x = points.shift();
y = points.shift();
data = "M" + x + "," + y + " L" + points.join(",");
if (type === "polygon") {
data += "," + x + "," + y + "z";
}
}
path.setAttribute("d", rawPathToString(path._gsRawPath = stringToRawPath(data)));
if (swap && element.parentNode) {
element.parentNode.insertBefore(path, element);
element.parentNode.removeChild(element);
}
return path;
}
//returns the rotation (in degrees) at a particular progress on a rawPath (the slope of the tangent)
export function getRotationAtProgress(rawPath, progress) {
let d = getProgressData(rawPath, progress >= 1 ? 1 - 1e-9 : progress ? progress : 1e-9);
return getRotationAtBezierT(d.segment, d.i, d.t);
}
function getRotationAtBezierT(segment, i, t) {
let a = segment[i],
b = segment[i+2],
c = segment[i+4],
x;
a += (b - a) * t;
b += (c - b) * t;
a += (b - a) * t;
x = b + ((c + (segment[i+6] - c) * t) - b) * t - a;
a = segment[i+1];
b = segment[i+3];
c = segment[i+5];
a += (b - a) * t;
b += (c - b) * t;
a += (b - a) * t;
return _round(_atan2(b + ((c + (segment[i+7] - c) * t) - b) * t - a, x) * _RAD2DEG);
}
export function sliceRawPath(rawPath, start, end) {
if (_isUndefined(end)) {
end = 1;
}
start = start || 0;
let reverse = start > end,
loops = Math.max(0, ~~(_abs(end - start) - 1e-8));
if (reverse) {
reverse = end;
end = start;
start = reverse;
reverse = 1;
loops -= loops ? 1 : 0;
}
if (start < 0 || end < 0) {
let offset = ~~Math.min(start, end) + 1;
start += offset;
end += offset;
}
let path = copyRawPath(rawPath.totalLength ? rawPath : cacheRawPathMeasurements(rawPath)),
wrap = (end > 1),
s = getProgressData(path, start, _temp),
e = getProgressData(path, end, _temp2),
eSeg = e.segment,
sSeg = s.segment,
eSegIndex = e.segIndex,
sSegIndex = s.segIndex,
ei = e.i,
si = s.i,
sameSegment = (sSegIndex === eSegIndex),
sameBezier = (ei === si && sameSegment),
invertedOrder = ((sameSegment && si > ei) || (sameBezier && s.t > e.t)),
sShift, eShift, i, copy, totalSegments, l, j;
if (wrap || loops) {
if (_splitSegment(path, sSegIndex, si, s.t)) {
sShift = 1;
sSegIndex++;
if (sameBezier) {
if (invertedOrder) {
e.t /= s.t;
} else {
e.t = (e.t - s.t) / (1 - s.t);
eSegIndex++;
ei = 0;
}
} else if (sSegIndex <= eSegIndex + 1 && !invertedOrder) {
eSegIndex++;
if (sameSegment) {
ei -= si;
}
}
}
if (!e.t) {
eSegIndex--;
if (reverse) {
sSegIndex--;
}
} else if (_splitSegment(path, eSegIndex, ei, e.t)) {
if (invertedOrder && sShift) {
sSegIndex++;
}
if (reverse) {
eSegIndex++;
}
}
copy = [];
totalSegments = path.length;
l = 1 + totalSegments * loops;
j = sSegIndex;
if (reverse) {
eSegIndex = (eSegIndex || totalSegments) - 1;
l += (totalSegments - eSegIndex + sSegIndex) % totalSegments;
for (i = 0; i < l; i++) {
_appendOrMerge(copy, path[j]);
j = (j || totalSegments) - 1;
}
} else {
l += ((totalSegments - sSegIndex) + eSegIndex) % totalSegments;
for (i = 0; i < l; i++) {
_appendOrMerge(copy, path[j++ % totalSegments]);
}
}
path = copy;
} else {
eShift = e.t === 1 ? 6 : subdivideSegment(eSeg, ei, e.t);
if (start !== end) {
sShift = subdivideSegment(sSeg, si, sameBezier ? s.t / e.t : s.t);
if (sameSegment) {
eShift += sShift;
}
eSeg.splice(ei + eShift + 2);
if (sShift) {
sSeg.splice(0, si + sShift);
}
i = path.length;
while (i--) {
//chop off any extra segments
if (i < sSegIndex || i > eSegIndex) {
path.splice(i, 1);
}
}
} else {
eSeg.angle = getRotationAtBezierT(eSeg, ei + eShift, 0); //record the value before we chop because it'll be impossible to determine the angle after its length is 0!
ei += eShift;
s = eSeg[ei];
e = eSeg[ei+1];
eSeg.length = eSeg.totalLength = 0;
eSeg.totalPoints = path.totalPoints = 8;
eSeg.push(s, e, s, e, s, e, s, e);
}
}
if (reverse) {
_reverseRawPath(path, wrap || loops);
}
path.totalLength = 0;
return path;
}
//measures a Segment according to its resolution (so if segment.resolution is 6, for example, it'll take 6 samples equally across each Bezier) and create/populate a "samples" array that has the length up to each of those sample points (always increasing from the start) as well as a "lookup" array that's broken up according to the smallest distance between 2 samples. This gives us a very fast way of looking up a progress position rather than looping through all the points/Beziers. You can optionally have it only measure a subset, starting at startIndex and going for a specific number of beziers (remember, there are 3 x/y pairs each, for a total of 6 elements for each Bezier). It will also populate a "totalLength" property, but that's not generally super accurate because by default it'll only take 6 samples per Bezier. But for performance reasons, it's perfectly adequate for measuring progress values along the path. If you need a more accurate totalLength, either increase the resolution or use the more advanced bezierToPoints() method which keeps adding points until they don't deviate by more than a certain precision value.
function measureSegment(segment, startIndex, bezierQty) {
startIndex = startIndex || 0;
if (!segment.samples) {
segment.samples = [];
segment.lookup = [];
}
let resolution = ~~segment.resolution || 12,
inc = 1 / resolution,
endIndex = bezierQty ? startIndex + bezierQty * 6 + 1 : segment.length,
x1 = segment[startIndex],
y1 = segment[startIndex + 1],
samplesIndex = startIndex ? (startIndex / 6) * resolution : 0,
samples = segment.samples,
lookup = segment.lookup,
min = (startIndex ? segment.minLength : _largeNum) || _largeNum,
prevLength = samples[samplesIndex + bezierQty * resolution - 1],
length = startIndex ? samples[samplesIndex-1] : 0,
i, j, x4, x3, x2, xd, xd1, y4, y3, y2, yd, yd1, inv, t, lengthIndex, l, segLength;
samples.length = lookup.length = 0;
for (j = startIndex + 2; j < endIndex; j += 6) {
x4 = segment[j + 4] - x1;
x3 = segment[j + 2] - x1;
x2 = segment[j] - x1;
y4 = segment[j + 5] - y1;
y3 = segment[j + 3] - y1;
y2 = segment[j + 1] - y1;
xd = xd1 = yd = yd1 = 0;
if (_abs(x4) < 1e-5 && _abs(y4) < 1e-5 && _abs(x2) + _abs(y2) < 1e-5) { //dump points that are sufficiently close (basically right on top of each other, making a bezier super tiny or 0 length)
if (segment.length > 8) {
segment.splice(j, 6);
j -= 6;
endIndex -= 6;
}
} else {
for (i = 1; i <= resolution; i++) {
t = inc * i;
inv = 1 - t;
xd = xd1 - (xd1 = (t * t * x4 + 3 * inv * (t * x3 + inv * x2)) * t);
yd = yd1 - (yd1 = (t * t * y4 + 3 * inv * (t * y3 + inv * y2)) * t);
l = _sqrt(yd * yd + xd * xd);
if (l < min) {
min = l;
}
length += l;
samples[samplesIndex++] = length;
}
}
x1 += x4;
y1 += y4;
}
if (prevLength) {
prevLength -= length;
for (; samplesIndex < samples.length; samplesIndex++) {
samples[samplesIndex] += prevLength;
}
}
if (samples.length && min) {
segment.totalLength = segLength = samples[samples.length-1] || 0;
segment.minLength = min;
l = lengthIndex = 0;
for (i = 0; i < segLength; i += min) {
lookup[l++] = (samples[lengthIndex] < i) ? ++lengthIndex : lengthIndex;
}
} else {
segment.totalLength = samples[0] = 0;
}
return startIndex ? length - samples[startIndex / 2 - 1] : length;
}
export function cacheRawPathMeasurements(rawPath, resolution) {
let pathLength, points, i;
for (i = pathLength = points = 0; i < rawPath.length; i++) {
rawPath[i].resolution = ~~resolution || 12; //steps per Bezier curve (anchor, 2 control points, to anchor)
points += rawPath[i].length;
pathLength += measureSegment(rawPath[i]);
}
rawPath.totalPoints = points;
rawPath.totalLength = pathLength;
return rawPath;
}
//divide segment[i] at position t (value between 0 and 1, progress along that particular cubic bezier segment that starts at segment[i]). Returns how many elements were spliced into the segment array (either 0 or 6)
export function subdivideSegment(segment, i, t) {
if (t <= 0 || t >= 1) {
return 0;
}
let ax = segment[i],
ay = segment[i+1],
cp1x = segment[i+2],
cp1y = segment[i+3],
cp2x = segment[i+4],
cp2y = segment[i+5],
bx = segment[i+6],
by = segment[i+7],
x1a = ax + (cp1x - ax) * t,
x2 = cp1x + (cp2x - cp1x) * t,
y1a = ay + (cp1y - ay) * t,
y2 = cp1y + (cp2y - cp1y) * t,
x1 = x1a + (x2 - x1a) * t,
y1 = y1a + (y2 - y1a) * t,
x2a = cp2x + (bx - cp2x) * t,
y2a = cp2y + (by - cp2y) * t;
x2 += (x2a - x2) * t;
y2 += (y2a - y2) * t;
segment.splice(i + 2, 4,
_round(x1a), //first control point
_round(y1a),
_round(x1), //second control point
_round(y1),
_round(x1 + (x2 - x1) * t), //new fabricated anchor on line
_round(y1 + (y2 - y1) * t),
_round(x2), //third control point
_round(y2),
_round(x2a), //fourth control point
_round(y2a)
);
if (segment.samples) {
segment.samples.splice(((i / 6) * segment.resolution) | 0, 0, 0, 0, 0, 0, 0, 0);
}
return 6;
}
// returns an object {path, segment, segIndex, i, t}
function getProgressData(rawPath, progress, decoratee) {
decoratee = decoratee || {};
if (!rawPath.totalLength) {
cacheRawPathMeasurements(rawPath);
}
if (progress < 0 || progress > 1) {
progress = _wrapProgress(progress);
}
let segIndex = 0,
segment = rawPath[0],
samples, resolution, length, min, max, i;
if (rawPath.length > 1) { //speed optimization: most of the time, there's only one segment so skip the recursion.
length = rawPath.totalLength * progress;
max = i = 0;
while ((max += rawPath[i++].totalLength) < length) {
segIndex = i;
}
segment = rawPath[segIndex];
min = max - segment.totalLength;
progress = ((length - min) / (max - min)) || 0;
}
samples = segment.samples;
resolution = segment.resolution; //how many samples per cubic bezier chunk
length = segment.totalLength * progress;
i = segment.lookup[~~(length / segment.minLength)] || 0;
min = i ? samples[i-1] : 0;
max = samples[i];
if (max < length) {
min = max;
max = samples[++i];
}
decoratee.path = rawPath;
decoratee.segment = segment;
decoratee.segIndex = segIndex;
decoratee.i = ~~(i / resolution) * 6;
decoratee.t = (1 / resolution) * (((length - min) / (max - min)) + ((i % resolution)));
return decoratee;
}
export function getPositionOnPath(rawPath, progress, includeAngle, point) {
let segment = rawPath[0],
result = point || {},
samples, resolution, length, min, max, i, t, a, inv;
if (progress < 0 || progress > 1) {
progress = _wrapProgress(progress);
}
if (rawPath.length > 1) { //speed optimization: most of the time, there's only one segment so skip the recursion.
length = rawPath.totalLength * progress;
max = i = 0;
while ((max += rawPath[i++].totalLength) < length) {
segment = rawPath[i];
}
min = max - segment.totalLength;
progress = ((length - min) / (max - min)) || 0;
}
samples = segment.samples;
resolution = segment.resolution;
length = segment.totalLength * progress;
i = segment.lookup[~~(length / segment.minLength)] || 0;
min = i ? samples[i-1] : 0;
max = samples[i];
if (max < length) {
min = max;
max = samples[++i];
}
t = ((1 / resolution) * (((length - min) / (max - min)) + ((i % resolution)))) || 0;
inv = 1 - t;
i = ~~(i / resolution) * 6;
a = segment[i];
result.x = _round((t * t * (segment[i + 6] - a) + 3 * inv * (t * (segment[i + 4] - a) + inv * (segment[i + 2] - a))) * t + a);
result.y = _round((t * t * (segment[i + 7] - (a = segment[i+1])) + 3 * inv * (t * (segment[i + 5] - a) + inv * (segment[i + 3] - a))) * t + a);
if (includeAngle) {
result.angle = segment.totalLength ? getRotationAtBezierT(segment, i, t >= 1 ? 1 - 1e-9 : t ? t : 1e-9) : segment.angle || 0;
}
return result;
}
//applies a matrix transform to RawPath (or a segment in a RawPath) and returns whatever was passed in (it transforms the values in the array(s), not a copy).
export function transformRawPath(rawPath, a, b, c, d, tx, ty) {
let j = rawPath.length,
segment, l, i, x, y;
while (--j > -1) {
segment = rawPath[j];
l = segment.length;
for (i = 0; i < l; i += 2) {
x = segment[i];
y = segment[i+1];
segment[i] = x * a + y * c + tx;
segment[i+1] = x * b + y * d + ty;
}
}
rawPath._dirty = 1;
return rawPath;
}
// translates SVG arc data into a segment (cubic beziers). Angle is in degrees.
function arcToSegment(lastX, lastY, rx, ry, angle, largeArcFlag, sweepFlag, x, y) {
if (lastX === x && lastY === y) {
return;
}
rx = _abs(rx);
ry = _abs(ry);
let angleRad = (angle % 360) * _DEG2RAD,
cosAngle = _cos(angleRad),
sinAngle = _sin(angleRad),
PI = Math.PI,
TWOPI = PI * 2,
dx2 = (lastX - x) / 2,
dy2 = (lastY - y) / 2,
x1 = (cosAngle * dx2 + sinAngle * dy2),
y1 = (-sinAngle * dx2 + cosAngle * dy2),
x1_sq = x1 * x1,
y1_sq = y1 * y1,
radiiCheck = x1_sq / (rx * rx) + y1_sq / (ry * ry);
if (radiiCheck > 1) {
rx = _sqrt(radiiCheck) * rx;
ry = _sqrt(radiiCheck) * ry;
}
let rx_sq = rx * rx,
ry_sq = ry * ry,
sq = ((rx_sq * ry_sq) - (rx_sq * y1_sq) - (ry_sq * x1_sq)) / ((rx_sq * y1_sq) + (ry_sq * x1_sq));
if (sq < 0) {
sq = 0;
}
let coef = ((largeArcFlag === sweepFlag) ? -1 : 1) * _sqrt(sq),
cx1 = coef * ((rx * y1) / ry),
cy1 = coef * -((ry * x1) / rx),
sx2 = (lastX + x) / 2,
sy2 = (lastY + y) / 2,
cx = sx2 + (cosAngle * cx1 - sinAngle * cy1),
cy = sy2 + (sinAngle * cx1 + cosAngle * cy1),
ux = (x1 - cx1) / rx,
uy = (y1 - cy1) / ry,
vx = (-x1 - cx1) / rx,
vy = (-y1 - cy1) / ry,
temp = ux * ux + uy * uy,
angleStart = ((uy < 0) ? -1 : 1) * Math.acos(ux / _sqrt(temp)),
angleExtent = ((ux * vy - uy * vx < 0) ? -1 : 1) * Math.acos((ux * vx + uy * vy) / _sqrt(temp * (vx * vx + vy * vy)));
if (isNaN(angleExtent)) { //rare edge case. Math.cos(-1) is NaN.
angleExtent = PI;
}
if (!sweepFlag && angleExtent > 0) {
angleExtent -= TWOPI;
} else if (sweepFlag && angleExtent < 0) {
angleExtent += TWOPI;
}
angleStart %= TWOPI;
angleExtent %= TWOPI;
let segments = Math.ceil(_abs(angleExtent) / (TWOPI / 4)),
rawPath = [],
angleIncrement = angleExtent / segments,
controlLength = 4 / 3 * _sin(angleIncrement / 2) / (1 + _cos(angleIncrement / 2)),
ma = cosAngle * rx,
mb = sinAngle * rx,
mc = sinAngle * -ry,
md = cosAngle * ry,
i;
for (i = 0; i < segments; i++) {
angle = angleStart + i * angleIncrement;
x1 = _cos(angle);
y1 = _sin(angle);
ux = _cos(angle += angleIncrement);
uy = _sin(angle);
rawPath.push(x1 - controlLength * y1, y1 + controlLength * x1, ux + controlLength * uy, uy - controlLength * ux, ux, uy);
}
//now transform according to the actual size of the ellipse/arc (the beziers were noramlized, between 0 and 1 on a circle).
for (i = 0; i < rawPath.length; i+=2) {
x1 = rawPath[i];
y1 = rawPath[i+1];
rawPath[i] = x1 * ma + y1 * mc + cx;
rawPath[i+1] = x1 * mb + y1 * md + cy;
}
rawPath[i-2] = x; //always set the end to exactly where it's supposed to be
rawPath[i-1] = y;
return rawPath;
}
//Spits back a RawPath with absolute coordinates. Each segment starts with a "moveTo" command (x coordinate, then y) and then 2 control points (x, y, x, y), then anchor. The goal is to minimize memory and maximize speed.
export function stringToRawPath(d) {
let a = (d + "").replace(_scientific, m => { let n = +m; return (n < 0.0001 && n > -0.0001) ? 0 : n; }).match(_svgPathExp) || [], //some authoring programs spit out very small numbers in scientific notation like "1e-5", so make sure we round that down to 0 first.
path = [],
relativeX = 0,
relativeY = 0,
twoThirds = 2 / 3,
elements = a.length,
points = 0,
errorMessage = "ERROR: malformed path: " + d,
i, j, x, y, command, isRelative, segment, startX, startY, difX, difY, beziers, prevCommand, flag1, flag2,
line = function(sx, sy, ex, ey) {
difX = (ex - sx) / 3;
difY = (ey - sy) / 3;
segment.push(sx + difX, sy + difY, ex - difX, ey - difY, ex, ey);
};
if (!d || !isNaN(a[0]) || isNaN(a[1])) {
console.log(errorMessage);
return path;
}
for (i = 0; i < elements; i++) {
prevCommand = command;
if (isNaN(a[i])) {
command = a[i].toUpperCase();
isRelative = (command !== a[i]); //lower case means relative
} else { //commands like "C" can be strung together without any new command characters between.
i--;
}
x = +a[i + 1];
y = +a[i + 2];
if (isRelative) {
x += relativeX;
y += relativeY;
}
if (!i) {
startX = x;
startY = y;
}
// "M" (move)
if (command === "M") {
if (segment) {
if (segment.length < 8) { //if the path data was funky and just had a M with no actual drawing anywhere, skip it.
path.length -= 1;
} else {
points += segment.length;
}
}
relativeX = startX = x;
relativeY = startY = y;
segment = [x, y];
path.push(segment);
i += 2;
command = "L"; //an "M" with more than 2 values gets interpreted as "lineTo" commands ("L").
// "C" (cubic bezier)
} else if (command === "C") {
if (!segment) {
segment = [0, 0];
}
if (!isRelative) {
relativeX = relativeY = 0;
}
//note: "*1" is just a fast/short way to cast the value as a Number. WAAAY faster in Chrome, slightly slower in Firefox.
segment.push(x, y, relativeX + a[i + 3] * 1, relativeY + a[i + 4] * 1, (relativeX += a[i + 5] * 1), (relativeY += a[i + 6] * 1));
i += 6;
// "S" (continuation of cubic bezier)
} else if (command === "S") {
difX = relativeX;
difY = relativeY;
if (prevCommand === "C" || prevCommand === "S") {
difX += relativeX - segment[segment.length - 4];
difY += relativeY - segment[segment.length - 3];
}
if (!isRelative) {
relativeX = relativeY = 0;
}
segment.push(difX, difY, x, y, (relativeX += a[i + 3] * 1), (relativeY += a[i + 4] * 1));
i += 4;
// "Q" (quadratic bezier)
} else if (command === "Q") {
difX = relativeX + (x - relativeX) * twoThirds;
difY = relativeY + (y - relativeY) * twoThirds;
if (!isRelative) {
relativeX = relativeY = 0;
}
relativeX += a[i + 3] * 1;
relativeY += a[i + 4] * 1;
segment.push(difX, difY, relativeX + (x - relativeX) * twoThirds, relativeY + (y - relativeY) * twoThirds, relativeX, relativeY);
i += 4;
// "T" (continuation of quadratic bezier)
} else if (command === "T") {
difX = relativeX - segment[segment.length - 4];
difY = relativeY - segment[segment.length - 3];
segment.push(relativeX + difX, relativeY + difY, x + ((relativeX + difX * 1.5) - x) * twoThirds, y + ((relativeY + difY * 1.5) - y) * twoThirds, (relativeX = x), (relativeY = y));
i += 2;
// "H" (horizontal line)
} else if (command === "H") {
line(relativeX, relativeY, (relativeX = x), relativeY);
i += 1;
// "V" (vertical line)
} else if (command === "V") {
//adjust values because the first (and only one) isn't x in this case, it's y.
line(relativeX, relativeY, relativeX, (relativeY = x + (isRelative ? relativeY - relativeX : 0)));
i += 1;
// "L" (line) or "Z" (close)
} else if (command === "L" || command === "Z") {
if (command === "Z") {
x = startX;
y = startY;
segment.closed = true;
}
if (command === "L" || _abs(relativeX - x) > 0.5 || _abs(relativeY - y) > 0.5) {
line(relativeX, relativeY, x, y);
if (command === "L") {
i += 2;
}
}
relativeX = x;
relativeY = y;
// "A" (arc)
} else if (command === "A") {
flag1 = a[i+4];
flag2 = a[i+5];
difX = a[i+6];
difY = a[i+7];
j = 7;
if (flag1.length > 1) { // for cases when the flags are merged, like "a8 8 0 018 8" (the 0 and 1 flags are WITH the x value of 8, but it could also be "a8 8 0 01-8 8" so it may include x or not)
if (flag1.length < 3) {
difY = difX;
difX = flag2;
j--;
} else {
difY = flag2;
difX = flag1.substr(2);
j-=2;
}
flag2 = flag1.charAt(1);
flag1 = flag1.charAt(0);
}
beziers = arcToSegment(relativeX, relativeY, +a[i+1], +a[i+2], +a[i+3], +flag1, +flag2, (isRelative ? relativeX : 0) + difX*1, (isRelative ? relativeY : 0) + difY*1);
i += j;
if (beziers) {
for (j = 0; j < beziers.length; j++) {
segment.push(beziers[j]);
}
}
relativeX = segment[segment.length-2];
relativeY = segment[segment.length-1];
} else {
console.log(errorMessage);
}
}
i = segment.length;
if (i < 6) { //in case there's odd SVG like a M0,0 command at the very end.
path.pop();
i = 0;
} else if (segment[0] === segment[i-2] && segment[1] === segment[i-1]) {
segment.closed = true;
}
path.totalPoints = points + i;
return path;
}
//populates the points array in alternating x/y values (like [x, y, x, y...] instead of individual point objects [{x, y}, {x, y}...] to conserve memory and stay in line with how we're handling segment arrays
export function bezierToPoints(x1, y1, x2, y2, x3, y3, x4, y4, threshold, points, index) {
let x12 = (x1 + x2) / 2,
y12 = (y1 + y2) / 2,
x23 = (x2 + x3) / 2,
y23 = (y2 + y3) / 2,
x34 = (x3 + x4) / 2,
y34 = (y3 + y4) / 2,
x123 = (x12 + x23) / 2,
y123 = (y12 + y23) / 2,
x234 = (x23 + x34) / 2,
y234 = (y23 + y34) / 2,
x1234 = (x123 + x234) / 2,
y1234 = (y123 + y234) / 2,
dx = x4 - x1,
dy = y4 - y1,
d2 = _abs((x2 - x4) * dy - (y2 - y4) * dx),
d3 = _abs((x3 - x4) * dy - (y3 - y4) * dx),
length;
if (!points) {
points = [x1, y1, x4, y4];
index = 2;
}
points.splice(index || points.length - 2, 0, x1234, y1234);
if ((d2 + d3) * (d2 + d3) > threshold * (dx * dx + dy * dy)) {
length = points.length;
bezierToPoints(x1, y1, x12, y12, x123, y123, x1234, y1234, threshold, points, index);
bezierToPoints(x1234, y1234, x234, y234, x34, y34, x4, y4, threshold, points, index + 2 + (points.length - length));
}
return points;
}
/*
function getAngleBetweenPoints(x0, y0, x1, y1, x2, y2) { //angle between 3 points in radians
var dx1 = x1 - x0,
dy1 = y1 - y0,
dx2 = x2 - x1,
dy2 = y2 - y1,
dx3 = x2 - x0,
dy3 = y2 - y0,
a = dx1 * dx1 + dy1 * dy1,
b = dx2 * dx2 + dy2 * dy2,
c = dx3 * dx3 + dy3 * dy3;
return Math.acos( (a + b - c) / _sqrt(4 * a * b) );
},
*/
//pointsToSegment() doesn't handle flat coordinates (where y is always 0) the way we need (the resulting control points are always right on top of the anchors), so this function basically makes the control points go directly up and down, varying in length based on the curviness (more curvy, further control points)
export function flatPointsToSegment(points, curviness=1) {
let x = points[0],
y = 0,
segment = [x, y],
i = 2;
for (; i < points.length; i+=2) {
segment.push(
x,
y,
points[i],
(y = (points[i] - x) * curviness / 2),
(x = points[i]),
-y
);
}
return segment;
}
//points is an array of x/y points, like [x, y, x, y, x, y]
export function pointsToSegment(points, curviness, cornerThreshold) {
//points = simplifyPoints(points, tolerance);
let l = points.length-2,
x = +points[0],
y = +points[1],
nextX = +points[2],
nextY = +points[3],
segment = [x, y, x, y],
dx2 = nextX - x,
dy2 = nextY - y,
prevX, prevY, angle, slope, i, dx1, dx3, dy1, dy3, d1, d2, a, b, c;
if (isNaN(cornerThreshold)) {
cornerThreshold = Math.PI / 10;
}
curviness = (curviness || curviness === 0) ? +curviness : 1;
for (i = 2; i < l; i+=2) {
prevX = x;
prevY = y;
x = nextX;
y = nextY;
nextX = +points[i+2];
nextY = +points[i+3];
dx1 = dx2;
dy1 = dy2;
dx2 = nextX - x;
dy2 = nextY - y;
dx3 = nextX - prevX;
dy3 = nextY - prevY;
a = dx1 * dx1 + dy1 * dy1;
b = dx2 * dx2 + dy2 * dy2;
c = dx3 * dx3 + dy3 * dy3;
angle = Math.acos( (a + b - c) / _sqrt(4 * a * b) ); //angle between the 3 points
d2 = (angle / Math.PI) * curviness; //temporary precalculation for speed (reusing d2 variable)
d1 = _sqrt(a) * d2; //the tighter the angle, the shorter we make the handles in proportion.
d2 *= _sqrt(b);
if (x !== prevX || y !== prevY) {
if (angle > cornerThreshold) {
slope = _atan2(dy3, dx3);
segment.push(
_round(x - _cos(slope) * d1), //first control point
_round(y - _sin(slope) * d1),
_round(x), //anchor
_round(y),
_round(x + _cos(slope) * d2), //second control point
_round(y + _sin(slope) * d2)
);
} else {
slope = _atan2(dy1, dx1);
segment.push(
_round(x - _cos(slope) * d1), //first control point
_round(y - _sin(slope) * d1));
slope = _atan2(dy2, dx2);
segment.push(
_round(x), //anchor
_round(y),
_round(x + _cos(slope) * d2), //second control point
_round(y + _sin(slope) * d2)
);
}
}
}
segment.push(_round(nextX), _round(nextY), _round(nextX), _round(nextY));
return segment;
}
//returns the squared distance between an x/y coordinate and a segment between x1/y1 and x2/y2
function pointToSegDist(x, y, x1, y1, x2, y2) {
let dx = x2 - x1,
dy = y2 - y1,
t;
if (dx || dy) {
t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x1 = x2;
y1 = y2;
} else if (t > 0) {
x1 += dx * t;
y1 += dy * t;
}
}
return (x - x1) ** 2 + (y - y1) ** 2;
}
function simplifyStep(points, first, last, tolerance, simplified) {
let maxSqDist = tolerance,
firstX = points[first],
firstY = points[first+1],
lastX = points[last],
lastY = points[last+1],
index, i, d;
for (i = first + 2; i < last; i += 2) {
d = pointToSegDist(points[i], points[i+1], firstX, firstY, lastX, lastY);
if (d > maxSqDist) {
index = i;
maxSqDist = d;
}
}
if (maxSqDist > tolerance) {
if (index - first > 2) {
simplifyStep(points, first, index, tolerance, simplified);
}
simplified.push(points[index], points[index+1]);
if (last - index > 2) {
simplifyStep(points, index, last, tolerance, simplified);
}
}
}
//points is an array of x/y values like [x, y, x, y, x, y]
export function simplifyPoints(points, tolerance) {
let prevX = parseFloat(points[0]),
prevY = parseFloat(points[1]),
temp = [prevX, prevY],
l = points.length - 2,
i, x, y, dx, dy, result, last;
tolerance = (tolerance || 1) ** 2;
for (i = 2; i < l; i += 2) {
x = parseFloat(points[i]);
y = parseFloat(points[i+1]);
dx = prevX - x;
dy = prevY - y;
if (dx * dx + dy * dy > tolerance) {
temp.push(x, y);
prevX = x;
prevY = y;
}
}
temp.push(parseFloat(points[l]), parseFloat(points[l+1]));
last = temp.length - 2;
result = [temp[0], temp[1]];
simplifyStep(temp, 0, last, tolerance, result);
result.push(temp[last], temp[last+1]);
return result;
}
function getClosestProgressOnBezier(iterations, px, py, start, end, slices, x0, y0, x1, y1, x2, y2, x3, y3) {
let inc = (end - start) / slices,
best = 0,
t = start,
x, y, d, dx, dy, inv;
_bestDistance = _largeNum;
while (t <= end) {
inv = 1 - t;
x = inv * inv * inv * x0 + 3 * inv * inv * t * x1 + 3 * inv * t * t * x2 + t * t * t * x3;
y = inv * inv * inv * y0 + 3 * inv * inv * t * y1 + 3 * inv * t * t * y2 + t * t * t * y3;
dx = x - px;
dy = y - py;
d = dx * dx + dy * dy;
if (d < _bestDistance) {
_bestDistance = d;
best = t;
}
t += inc;
}
return (iterations > 1) ? getClosestProgressOnBezier(iterations - 1, px, py, Math.max(best - inc, 0), Math.min(best + inc, 1), slices, x0, y0, x1, y1, x2, y2, x3, y3) : best;
}
export function getClosestData(rawPath, x, y, slices) { //returns an object with the closest j, i, and t (j is the segment index, i is the index of the point in that segment, and t is the time/progress along that bezier)
let closest = {j:0, i:0, t:0},
bestDistance = _largeNum,
i, j, t, segment;
for (j = 0; j < rawPath.length; j++) {
segment = rawPath[j];
for (i = 0; i < segment.length; i+=6) {
t = getClosestProgressOnBezier(1, x, y, 0, 1, slices || 20, segment[i], segment[i+1], segment[i+2], segment[i+3], segment[i+4], segment[i+5], segment[i+6], segment[i+7]);
if (bestDistance > _bestDistance) {
bestDistance = _bestDistance;
closest.j = j;
closest.i = i;
closest.t = t;
}
}
}
return closest;
}
//subdivide a Segment closest to a specific x,y coordinate
export function subdivideSegmentNear(x, y, segment, slices, iterations) {
let l = segment.length,
bestDistance = _largeNum,
bestT = 0,
bestSegmentIndex = 0,
t, i;
slices = slices || 20;
iterations = iterations || 3;
for (i = 0; i < l; i += 6) {
t = getClosestProgressOnBezier(1, x, y, 0, 1, slices, segment[i], segment[i+1], segment[i+2], segment[i+3], segment[i+4], segment[i+5], segment[i+6], segment[i+7]);
if (bestDistance > _bestDistance) {
bestDistance = _bestDistance;
bestT = t;
bestSegmentIndex = i;
}
}
t = getClosestProgressOnBezier(iterations, x, y, bestT - 0.05, bestT + 0.05, slices, segment[bestSegmentIndex], segment[bestSegmentIndex+1], segment[bestSegmentIndex+2], segment[bestSegmentIndex+3], segment[bestSegmentIndex+4], segment[bestSegmentIndex+5], segment[bestSegmentIndex+6], segment[bestSegmentIndex+7]);
subdivideSegment(segment, bestSegmentIndex, t);
return bestSegmentIndex + 6;
}
/*
Takes any of the following and converts it to an all Cubic Bezier SVG data string:
- A <path> data string like "M0,0 L2,4 v20,15 H100"
- A RawPath, like [[x, y, x, y, x, y, x, y][[x, y, x, y, x, y, x, y]]
- A Segment, like [x, y, x, y, x, y, x, y]
Note: all numbers are rounded down to the closest 0.001 to minimize memory, maximize speed, and avoid odd numbers like 1e-13
*/
export function rawPathToString(rawPath) {
if (_isNumber(rawPath[0])) { //in case a segment is passed in instead
rawPath = [rawPath];
}
let result = "",
l = rawPath.length,
sl, s, i, segment;
for (s = 0; s < l; s++) {
segment = rawPath[s];
result += "M" + _round(segment[0]) + "," + _round(segment[1]) + " C";
sl = segment.length;
for (i = 2; i < sl; i++) {
result += _round(segment[i++]) + "," + _round(segment[i++]) + " " + _round(segment[i++]) + "," + _round(segment[i++]) + " " + _round(segment[i++]) + "," + _round(segment[i]) + " ";
}
if (segment.closed) {
result += "z";
}
}
return result;
}
/*
// takes a segment with coordinates [x, y, x, y, ...] and converts the control points into angles and lengths [x, y, angle, length, angle, length, x, y, angle, length, ...] so that it animates more cleanly and avoids odd breaks/kinks. For example, if you animate from 1 o'clock to 6 o'clock, it'd just go directly/linearly rather than around. So the length would be very short in the middle of the tween.
export function cpCoordsToAngles(segment, copy) {
var result = copy ? segment.slice(0) : segment,
x, y, i;
for (i = 0; i < segment.length; i+=6) {
x = segment[i+2] - segment[i];
y = segment[i+3] - segment[i+1];
result[i+2] = Math.atan2(y, x);
result[i+3] = Math.sqrt(x * x + y * y);
x = segment[i+6] - segment[i+4];
y = segment[i+7] - segment[i+5];
result[i+4] = Math.atan2(y, x);
result[i+5] = Math.sqrt(x * x + y * y);
}
return result;
}
// takes a segment that was converted with cpCoordsToAngles() to have angles and lengths instead of coordinates for the control points, and converts it BACK into coordinates.
export function cpAnglesToCoords(segment, copy) {
var result = copy ? segment.slice(0) : segment,
length = segment.length,
rnd = 1000,
angle, l, i, j;
for (i = 0; i < length; i+=6) {
angle = segment[i+2];
l = segment[i+3]; //length
result[i+2] = (((segment[i] + Math.cos(angle) * l) * rnd) | 0) / rnd;
result[i+3] = (((segment[i+1] + Math.sin(angle) * l) * rnd) | 0) / rnd;
angle = segment[i+4];
l = segment[i+5]; //length
result[i+4] = (((segment[i+6] - Math.cos(angle) * l) * rnd) | 0) / rnd;
result[i+5] = (((segment[i+7] - Math.sin(angle) * l) * rnd) | 0) / rnd;
}
return result;
}
//adds an "isSmooth" array to each segment and populates it with a boolean value indicating whether or not it's smooth (the control points have basically the same slope). For any smooth control points, it converts the coordinates into angle (x, in radians) and length (y) and puts them into the same index value in a smoothData array.
export function populateSmoothData(rawPath) {
let j = rawPath.length,
smooth, segment, x, y, x2, y2, i, l, a, a2, isSmooth, smoothData;
while (--j > -1) {
segment = rawPath[j];
isSmooth = segment.isSmooth = segment.isSmooth || [0, 0, 0, 0];
smoothData = segment.smoothData = segment.smoothData || [0, 0, 0, 0];
isSmooth.length = 4;
l = segment.length - 2;
for (i = 6; i < l; i += 6) {
x = segment[i] - segment[i - 2];
y = segment[i + 1] - segment[i - 1];
x2 = segment[i + 2] - segment[i];
y2 = segment[i + 3] - segment[i + 1];
a = _atan2(y, x);
a2 = _atan2(y2, x2);
smooth = (Math.abs(a - a2) < 0.09);
if (smooth) {
smoothData[i - 2] = a;
smoothData[i + 2] = a2;
smoothData[i - 1] = _sqrt(x * x + y * y);
smoothData[i + 3] = _sqrt(x2 * x2 + y2 * y2);
}
isSmooth.push(smooth, smooth, 0, 0, smooth, smooth);
}
//if the first and last points are identical, check to see if there's a smooth transition. We must handle this a bit differently due to their positions in the array.
if (segment[l] === segment[0] && segment[l+1] === segment[1]) {
x = segment[0] - segment[l-2];
y = segment[1] - segment[l-1];
x2 = segment[2] - segment[0];
y2 = segment[3] - segment[1];
a = _atan2(y, x);
a2 = _atan2(y2, x2);
if (Math.abs(a - a2) < 0.09) {
smoothData[l-2] = a;
smoothData[2] = a2;
smoothData[l-1] = _sqrt(x * x + y * y);
smoothData[3] = _sqrt(x2 * x2 + y2 * y2);
isSmooth[l-2] = isSmooth[l-1] = true; //don't change indexes 2 and 3 because we'll trigger everything from the END, and this will optimize file size a bit.
}
}
}
return rawPath;
}
export function pointToScreen(svgElement, point) {
if (arguments.length < 2) { //by default, take the first set of coordinates in the path as the point
let rawPath = getRawPath(svgElement);
point = svgElement.ownerSVGElement.createSVGPoint();
point.x = rawPath[0][0];
point.y = rawPath[0][1];
}
return point.matrixTransform(svgElement.getScreenCTM());
}
*/ |
// Original source: http://webdeveloper.earthweb.com/repository/javascripts/2005/03/660841/vergrootglas.html
//
// Changes and improvements:
// - supports multiple images, anywhere on page, not just at top
// - calculates magnification from the image width's
// - supports non-square individually-sized magnifiers
// - uses standardized methods for event capture if available (captureEvents
// disappearing in Firefox 3)
// - replaces clip rect with clipping div's because clip computed style not well
// supported in Safari 3 or IE 7 (thanks, dhtml)
// - more modular code, no public names
// Put code inside function to avoid conflict with other Javascript
// - http://www.davidflanagan.com/blog/2005_07.html
//
// At end of file, change true to false if you want to silence error messages
// from missing image information.
//
// Exported function:
// MAGNIFIER.data() - returns the array of image data being used
// MAGNIFIER.reset() - rescans for images (used by magnifier_maker.html)
var MAGNIFIER = function (alertOnErrors) {
// Default magnifier is 150 wide by 150 high.
// It can be overridden by an inline clip rect on a specific large image.
//
// Reminder: clip rect numbers are top, right, bottom, and left.
// px is required. While commas are correct, they are not accepted by IE.
// Browsers are encouraged by W3C to handle the non-comma version.
var defaultClipRect = "rect(0px 150px 150px 0px)";
var defaultClipWidth = 150;
var defaultClipHeight = 150;
// For internal use
//
// imagePairData: a list of data about all small / large image pairs.
// Calculated at load time, each element data contains:
//
// data.small - the small image, with position and size
// data.large - the large magnified image and its size
// data.mag - the x and y magnification factors
// data.lens - the maglens div object with width and height
// data.rect - the clipping rectangle with width and height
// -- only one of data.lens and data.rect should exist
var imagePairData = [];
// currentImagePair: the imagePairData for the item currently being magnified, if any
var currentImagePair;
// Simon Willison's addLoadEvent -- http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(fn) {
var oldfn = window.onload;
window.onload = (typeof oldfn != 'function') ? fn : function() { oldfn(); fn(); };
}
// center the magnifier lens on x, y
function centerLens(data, x, y) {
var lens = data.lens.node;
lens.style.left = (x - (data.lens.width / 2)) + "px";
lens.style.top = (y - (data.lens.height / 2)) + "px";
}
// create a rect() from a rect() with same size but centered on x,y
function centerRect(rect, x, y) {
var dx = Math.round(rect.width / 2);
var dy = Math.round(rect.height / 2);
return "rect(" + (y - dy) + "px " + (x + dx) + "px " + (y + dy) + "px " + (x - dx) + "px)";
}
function findImagePairData(x, y) {
for (var i = 0; i < imagePairData.length; ++i) {
if (imagePairData[i].contains(x, y)) {
return imagePairData[i];
}
}
return null;
}
// Don't use getCurrentStyle() -- Opera 9.5 calculates a zero-sized clipping
// rectangle as a default.
function getClipRect(node) {
var rect = node.style.clip || defaultClipRect;
var matches = /([\-.0-9]+)[^\-.0-9]+([\-.0-9]+)[^\-.0-9]+([\-.0-9]+)[^\-.0-9]+([\-.0-9]+)/.exec(rect);
var top = + matches[1];
var right = + matches[2];
var bottom = + matches[3];
var left = + matches[4];
var width = !(left || right) ? defaultClipWidth : right - left;
var height = !(top || bottom) ? defaultClipHeight : bottom - top;
return { width: width, height: height };
}
// try every place style info might be
function getCurrentStyle(elt, property) {
var dv = document.defaultView && document.defaultView.getComputedStyle &&
document.defaultView.getComputedStyle(elt, null)[property];
var cs = elt.currentStyle && elt.currentStyle[property] && elt.currentStyle[property];
var rs = elt.runtimeStyle && elt.runtimeStyle[property] && elt.runtimeStyle[property];
var es = elt.style && elt.style[property] && elt.style[property];
return dv || cs || rs || es;
}
function getComputedValue(elt, property) {
return parseFloat(getCurrentStyle(elt, property));
}
function getImagePairData(x, y) {
// reuse current data if possible
if (currentImagePair) {
if (currentImagePair.contains(x, y)) {
return currentImagePair;
}
// don't search for another if only one pair
else if (imagePairData.length < 2) {
return null;
}
}
else {
return findImagePairData(x, y);
}
}
function getInlineValue(elt, property) {
return parseFloat(elt.style[property] || elt[property]);
}
// Return something useful as a label in error messages
function getLabel(node) {
return node.id || node.name || node.src || node;
}
function getLargeImages() {
var largeImages = [];
for (var i = 0; i < document.images.length; ++i) {
if (isLargeImage(document.images[i])) {
largeImages[largeImages.length] = document.images[i];
}
}
return largeImages;
}
function getLens(image) {
if (image && isLens(image.parentNode)) {
var node = image.parentNode;
return {
node: node,
width: getComputedValue(node, "width"),
height: getComputedValue(node, "height")
};
}
else {
return null;
}
}
function getMagnifierParent(node) {
var parent = node.parentNode;
if (isLens(parent)) {
parent = parent.parentNode;
}
return parent;
}
function getOffset(obj, field) {
var sum = 0;
do { sum += obj[field]; }
while ((obj = obj.offsetParent));
return sum;
}
function getSmallImage(largeImage) {
var parent = getMagnifierParent(largeImage);
var images = parent.getElementsByTagName("IMG");
for (var i = 0; i < images.length; ++i) {
if (isSmallImage(images[i])) {
return images[i];
}
}
return null;
}
function hideMagnifiedImage(image) {
image.style.display = "none";
}
function isLargeImage(image) {
return image.className == "maglarge" || nameStartsWith(image, "large");
}
function isLens(node) {
return node && (node.className == "maglens" || nameStartsWith(node, "lens"));
}
function isSmallImage(image) {
return image.className == "magsmall" || nameStartsWith(image, "small");
}
function magAlert(msg) {
if (alertOnErrors) {
alert("Magnifier error: " + msg);
}
}
// Pair the large image with the small image in the same container. If
// there is no small image, create one. Return an object with data on
// the images, magnifier lens, and magnification factor.
function makeImagePairData(i, largeImage) {
if (!largeImage) {
magAlert("No large image for magnifier " + (i + 1));
return null;
}
var imageLabel = "image: " + getLabel(largeImage);
// There's either a clipping maglens DIV...
var lens = getLens(largeImage);
if (lens && (!lens.width || !lens.height || isNaN(lens.width) || isNaN(lens.height))) {
magAlert("Can't get lens dimensions for " + imageLabel);
return null;
}
// ... or a clipping rectangle on the large image.
var rect = lens ? null : getClipRect(largeImage);
if (rect && (!rect.width || !rect.height || isNaN(rect.width) || isNaN(rect.height))) {
magAlert("Can't get clip dimensions for " + imageLabel);
return null;
}
// The size of the small image is set by the parent DIV.
var parent = getMagnifierParent(largeImage);
if (!parent) {
magAlert("No parent DIV found for " + imageLabel);
return null;
}
// There's either a small image given, or one is constructed.
var smallImage = getSmallImage(largeImage) ||
makeSmallImage(largeImage, parent, lens ? lens.node : largeImage);
if (!smallImage) {
magAlert("No small image for " + imageLabel);
return null;
}
var sx = getOffset(smallImage, "offsetLeft");
var sy = getOffset(smallImage, "offsetTop");
var sw = getInlineValue(parent, "width");
var sh = getInlineValue(parent, "height");
if (isNaN(sw) || isNaN(sh)) {
magAlert("Can't get small image dimensions for " + imageLabel);
return null;
}
else {
smallImage.width = sw;
smallImage.height = sh;
}
// The size of the large image is specifed on the image.
var lw = getInlineValue(largeImage, "width");
var lh = getInlineValue(largeImage, "height");
if (!lw || !lh) {
magAlert("Can't get large image dimensions for " + imageLabel);
return null;
}
return {
small: { image: smallImage, x: sx, y: sy, width: sw, height: sh },
large: { image: largeImage, width: lw, height: lh },
mag: { x: lw / sw, y: lh / sh },
lens: lens,
rect: rect,
contains: function(x, y) {
return (sx <= x && x <= sx + sw && sy <= y && y <= sy + sh);
}
};
}
// Passed the largeImage to copy, and where to insert it.
function makeSmallImage(largeImage, parent, refChild) {
if (refChild.parentNode != parent) {
magAlert("Problem getting parent DIV for " + getLabel(largeImage));
return null;
}
var smallImage = new Image();
smallImage.className = "magsmall";
smallImage.style.position = "absolute";
smallImage.style.top = "0px";
smallImage.style.left = "0px";
smallImage.style.width = parent.style.width;
smallImage.style.height = parent.style.height;
smallImage.style.borderStyle = "none";
// IE flashes the large image on insertion unless hidden
smallImage.style.display = "none";
smallImage.src = largeImage.src;
parent.insertBefore(smallImage, refChild);
smallImage.style.display = "block";
return smallImage;
}
function mouseTrack(evt) {
var x, y;
if (evt && !(evt.pageX === undefined)) {
x = evt.pageX;
y = evt.pageY;
evt.stopPropagation();
}
else { // Internet Explorer
x = event.clientX + (document.body.scrollLeft || document.documentElement.scrollLeft) - document.body.clientLeft;
y = event.clientY + (document.body.scrollTop || document.documentElement.scrollTop) - document.body.clientTop;
event.cancelBubble = true;
}
var data = getImagePairData(x, y);
if (data) {
updateMagnifiedImage(x, y, data);
}
else if (currentImagePair) {
hideMagnifiedImage(currentImagePair.large.image);
currentImagePair = null;
}
}
function nameStartsWith(node, name) {
return startsWith(node.name, name) || startsWith(node.id, name);
}
function startsWith(str1, str2) {
return str1 && str2 !== undefined && str2 !== null && str1.indexOf(str2) === 0;
}
function updateMagnifiedImage(x, y, data) {
// upper left of small image
var sx = data.small.x;
var sy = data.small.y;
// mouse x,y relative to small image
var rx = x - sx;
var ry = y - sy;
// mouse x, y relative to large image
var Rx = Math.floor(rx * data.mag.x);
var Ry = Math.floor(ry * data.mag.y);
var Sx, Sy;
var largeStyle = data.large.image.style;
// if using lens div
if (data.lens) {
// position lens
centerLens(data, rx, ry);
// then calculate upper left of large image relative to lens div
Sx = x - Rx - getOffset(data.lens.node, "offsetLeft");
Sy = y - Ry - getOffset(data.lens.node, "offsetTop");
}
else { // if using clip rect
// position clip region
largeStyle.clip = centerRect(data.rect, Rx, Ry);
// then calculate upper left of large image relative to magnifier div
Sx = x - Rx - sx;
Sy = y - Ry - sy;
}
largeStyle.left = Sx + "px";
largeStyle.top = Sy + "px";
// window.status = "xy (" + x + "," + y + ") sxy (" + sx + "," + sy + ") rxy (" + rx + "," + ry + ") Rxy (" + Rx + "," + Ry + ") Sy (" + Sx + "," + Sy + ")";
largeStyle.display = "block";
currentImagePair = data;
}
// Set up mousetracking; support W3C standard and IE
function initListeners() {
if (document.addEventListener) {
document.addEventListener('mousemove', mouseTrack, true);
}
else if (document.attachEvent) {
document.attachEvent('onmousemove', mouseTrack);
}
else {
if (!document.all) {
document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = mouseTrack;
}
}
// Create magnifier data for every "large" image.
function registerImagePairs() {
// Careful! makeImagePairData() inserts small images before the large
// images so collect large images first to avoid endless insertion.
var largeImages = getLargeImages();
imagePairData = [];
for (var i = 0; i < largeImages.length; ++i) {
var data = makeImagePairData(i, largeImages[i]);
if (data) {
imagePairData[imagePairData.length] = data;
hideMagnifiedImage(largeImages[i]);
}
}
}
// javascript:MAGNIFIER.status()
function makeStatusString() {
var missing = [];
var i = 0;
var testImage = function(i) {
if (i < imagePairData.length) {
img.src = imagePairData[i].large.image.src;
}
else {
showImageSummary(missing);
}
}
var img = new Image();
img.onerror = function (evt) {
missing[missing.length] = this.src;
testImage(++i);
}
img.onload = function (evt) {
testImage(++i);
}
testImage(i);
return "Number of magnified images: " + imagePairData.length + "\n";
}
function showImageSummary(missing) {
var text = "";
for (var i = 0; i < missing.length; ++i) {
text += "\n " + makeRelativePath(missing[i]) + " not found";
}
alert(text);
}
function makeRelativePath(url) {
var locParts = window.location.href.split("/");
var urlParts = url.split("/");
var i = 0;
while (i < locParts.length && locParts[i] == urlParts[i]) {
++i;
}
if (i == 0) {
return url;
}
else {
var relUrl = urlParts.slice(i).join("/");
while (++i < locParts.length) {
relUrl = "../" + relUrl;
}
return relUrl;
}
}
// startup code adds onload events to get image data and start mouse tracking
addLoadEvent(function () {
registerImagePairs();
initListeners();
});
return {
data: function () { return imagePairData; },
reset: function() { registerImagePairs(); },
status: function() { alert(makeStatusString()); }
};
// End private function; call it to initialize event handlers
// Change true to false to silence errors noticed in loading images
}(true);
|
import {physx, Phys3D} from './Physx';
Bridge.assembly("unity-script-converter", function ($asm, globals) {
"use strict";
Bridge.define("MiniGameAdaptor.PhysicMaterialCombine", {
$kind: "enum",
statics: {
fields: {
Average: 0,
Minimum: 2,
Multiply: 1,
Maximum: 3
}
}
});
});
Bridge.assembly("unity-script-converter", function ($asm, globals) {
"use strict";
Bridge.define("MiniGameAdaptor.PhysicMaterial", {
inherits: [MiniGameAdaptor.Object],
props: {
bounceCombine: {
get: function () {
return this.nativeMaterial.bounceCombine;
},
set: function (value) {
this.nativeMaterial.bounceCombine = value;
}
},
bounciness: {
get: function () {
return this.nativeMaterial.bounciness;
},
set: function (value) {
this.nativeMaterial.bounciness = value;
}
},
dynamicFriction: {
get: function () {
return this.nativeMaterial.dynamicFriction;
},
set: function (value) {
this.nativeMaterial.dynamicFriction = value;
}
},
frictionCombine: {
get: function () {
return this.nativeMaterial.frictionCombine;
},
set: function (value) {
this.nativeMaterial.frictionCombine = value;
}
},
staticFriction: {
get: function () {
return this.nativeMaterial.staticFriction;
},
set: function (value) {
this.nativeMaterial.staticFriction = value;
}
}
},
ctors: {
ctor: function () {
this.$initialize();
UnityEngine.Object.ctor.call(this);
const instance = physx.Phys3dInstance;
// https://docs.unity3d.com/Manual/class-PhysicMaterial.html
this.nativeMaterial = new Phys3D.Material(instance);
},
$ctor1: function (name) {
this.$initialize();
UnityEngine.Object.ctor.call(this);
// https://docs.unity3d.com/Manual/class-PhysicMaterial.html
this.nativeMaterial = new Phys3D.Material(instance);
}
}
});
});
|
import ReactionError from "@reactioncommerce/reaction-error";
import SimpleSchema from "simpl-schema";
import generateVerificationTokenObject from "@reactioncommerce/api-utils/generateVerificationTokenObject.js";
const inputSchema = new SimpleSchema({
email: String,
userId: String
});
/**
* @name authentication/startIdentityPasswordReset
* @memberof Mutations/Authentication
* @summary Start an email verification by generating a token, saving it to the user
* record, and returning it. This mutation is only intended to be called internally
* by other plugins.
* @param {Object} context - App context
* @param {Object} input - Input arguments
* @param {String} input.email - Email address to verify. Must be an address the user has.
* @param {String} input.userId - The user ID
* @return {Promise<Object>} Object with `token` key
*/
export default async function startIdentityPasswordReset(context, input) {
inputSchema.validate(input);
const { collections: { users } } = context;
const { email, userId } = input;
// Make sure the user exists, and email is one of their addresses.
const user = await users.findOne({ _id: userId });
if (!user) throw new ReactionError("not-found", "User not found");
// make sure we have a valid email
if (!email || !user.emails || !user.emails.map((mailInfo) => mailInfo.address).includes(email)) {
throw new ReactionError("not-found", "Email not found");
}
// Create token for password reset
const tokenObj = generateVerificationTokenObject({ email });
try {
await users.updateOne({ _id: userId }, {
$set: {
"services.password.reset": tokenObj
}
});
} catch (error) {
throw new ReactionError("error-occurred", "Unable to set password reset token");
}
return { token: tokenObj.token };
}
|
import sys
import json
class Memory:
def __init__(self, i, f, s, b):
self.ints = [None] * int(i)
self.floats = [None] * int(f)
self.strings = [None] * int(s)
self.bools = [None] * int(b)
def insert_ints(self, arr_ints):
for idx, values in enumerate(arr_ints):
self.ints[idx] = int(values)
def insert_floats(self, arr_floats):
for idx, values in enumerate(arr_floats):
self.floats[idx] = float(values)
def insert_strings(self, arr_string):
for idx, values in enumerate(arr_string):
self.strings[idx] = values
def insert_bools(self, arr_bools):
for idx, values in enumerate(arr_bools):
self.bools[idx] = values == 'true'
def get_value_of_address(self, address):
if address < 300:
return int(self.ints[address])
elif address < 600:
return self.floats[address % 300]
elif address < 900:
return self.strings[address % 300]
else:
return self.bools[address % 300]
def set_value_in_address(self, address, value):
if address < 300:
self.ints[address] = value
elif address < 600:
self.floats[address % 300] = value
elif address < 900:
self.strings[address % 300] = value
else:
self.bools[address % 300] = value
def set_param_value_in_addres(self, value, type):
if type == '0':
idx = next(idx for idx, item in enumerate(
self.ints) if item is None)
self.ints[idx] = value
elif type == '1':
idx = next(idx for idx, item in enumerate(
self.floats) if item is None)
self.floats[idx] = value
elif type == '2':
idx = next(idx for idx, item in enumerate(
self.strings) if item is None)
self.strings[idx] = value
else:
idx = next(idx for idx, item in enumerate(
self.bools) if item is None)
self.bools[idx] = value
func_dir = {}
class_dir = {}
ip = 1
local_mems = []
temp_mems = []
global_mem = None
constants_mem = None
aux_loc_mem = None
aux_temp_mem = None
next_func = None
ip_stack = []
read_values_stack = []
class_mem = None
def reconstruct_func_dir(line):
name, _rt, num_types, params, num_temps, start, *_ = line.split(' ')
if name == 'main':
func_dir[name] = {'num_types': num_types, 'num_temps': num_temps}
else:
func_dir[name] = {'num_types': num_types,
'num_temps': num_temps, 'start': start, 'params': params}
def reconstruct_class_dir(line, class_name):
name, _rt, num_types, _params, start, *_ = line.split(' ')
class_dir[class_name][name] = {'num_types': num_types, 'start': start}
def initialize_constant_mem(infile):
_, *values = infile.readline().rstrip('\n').split('\u001f')
ints = values[0:-1]
_, *values = infile.readline().rstrip('\n').split('\u001f')
floats = values[0:-1]
_, *values = infile.readline().rstrip('\n').split('\u001f')
strings = values[0:-1]
_, *values = infile.readline().rstrip('\n').split('\u001f')
bools = values[0:-1]
constants_mem = Memory(len(ints), len(
floats), len(strings), len(bools))
constants_mem.insert_ints(ints)
constants_mem.insert_floats(floats)
constants_mem.insert_strings(strings)
constants_mem.insert_bools(bools)
return constants_mem
def get_actual_value(address):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
if int(address) >= 6000:
prev_local_mem = local_mems[-2]
addr = class_mem.get_value_of_address(int(address) % 1500)
if int(addr) // 1500 == 1:
val = prev_local_mem.get_value_of_address(
int(addr) % 1500)
else:
val = memories[str(int(address) // 1500)
].get_value_of_address(int(addr) % 1500)
else:
val = memories[str(int(address) // 1500)
].get_value_of_address(int(address) % 1500)
return val
def do_addition(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
sum_res = left_dir_val + right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, sum_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, sum_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, sum_res)
def do_multiplication(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val * right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def do_subtraction(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val - right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def do_division(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val / right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def compare_gt(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val > right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def compare_lt(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val < right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def compare_eq(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val == right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def compare_ne(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val != right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def compare_geq(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val >= right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def compare_leq(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val <= right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def do_or(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val or right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def do_and(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
left_dir_val = get_actual_value(left)
right_dir_val = get_actual_value(right)
if left_dir_val == None or right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
mult_res = left_dir_val and right_dir_val
if int(res) >= 6000:
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, mult_res)
else:
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, mult_res)
def do_goto(_, __, res):
global ip
ip = int(res)
def do_assignment(left, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem,
'4': class_mem
}
if int(res) >= 6000:
if int(right) == -1:
left_dir_val = memories[str(int(left) // 1500)
].get_value_of_address(int(left) % 1500)
if left_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
prev_local_mem = local_mems[-2]
res = class_mem.get_value_of_address(int(res) % 1500)
mem = int(res) // 1500
if mem == 1:
prev_local_mem.set_value_in_address(int(res) %
1500, left_dir_val)
else:
memories[str(mem)].set_value_in_address(int(res) %
1500, left_dir_val)
else:
class_mem.set_value_in_address(int(res) %
1500, int(left))
else:
left_dir_val = memories[str(int(left) // 1500)
].get_value_of_address(int(left) % 1500)
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, left_dir_val)
def do_goto_f(_, right, res):
global ip
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem
}
right_dir_val = memories[str(int(right) // 1500)
].get_value_of_address(int(right) % 1500)
if right_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
ip = int(res) if right_dir_val == False else ip + 1
def do_gosub(left, _, __):
global ip, local_mems, temp_mems, ip_stack
local_mems.append(aux_loc_mem)
temp_mems.append(aux_temp_mem)
if len(local_mems) > 25:
print('Stack overflow')
exit(1)
ip_stack.append(ip)
ip = int(func_dir[left]['start'])
def do_era(left, _, __):
global aux_loc_mem, aux_temp_mem, next_func, class_mem
left_split = left.split('.')
next_func = left
ints, floats, strings, bools, _voids, * \
_ = func_dir[left]['num_types'].split('\u001f')
aux_loc_mem = Memory(ints, floats, strings, bools)
ints, floats, strings, bools, _voids, * \
_ = func_dir[left]['num_temps'].split('\u001f')
aux_temp_mem = Memory(ints, floats, strings, bools)
if len(left_split) > 1:
ints, floats, strings, bools, _voids, * \
_ = class_dir[left_split[0]]['num_types'].split('\u001f')
class_mem = Memory(ints, floats, strings, bools)
# print(json.dumps(class_dir, indent=2))
# ints, floats, strings, bools, _voids, *_ = class_dir
def do_param(left, _, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem
}
left_dir_val = memories[str(int(left) // 1500)
].get_value_of_address(int(left) % 1500)
if left_dir_val == None:
raise ReferenceError("Value in variable has not been assigned")
param_type = func_dir[next_func]['params'][int(res)]
aux_loc_mem.set_param_value_in_addres(left_dir_val, param_type)
def do_print(_, __, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem
}
res_dir_val = memories[str(int(res) // 1500)
].get_value_of_address(int(res) % 1500)
if isinstance(res_dir_val, str):
s = str.split(res_dir_val, '\\n')
for i in range(len(s) - 1):
sys.stdout.write(s[i] + '\n')
if s[-1] == '':
sys.stdout.write(s[-1])
else:
sys.stdout.write(s[-1] + ' ')
else:
sys.stdout.write(str(res_dir_val) + ' ')
def do_endfunc(_, __, ___):
global ip, local_mems, temp_mems, ip_stack
local_mems.pop()
temp_mems.pop()
ip = ip_stack.pop()
def do_return(left, _, res):
global ip, local_mems, temp_mems, ip_stack
do_assignment(left, _, res)
local_mems.pop()
temp_mems.pop()
ip = ip_stack.pop()
def do_end(_, __, ___):
exit(0)
def do_read(_, __, res):
if len(read_values_stack) == 0:
in_line = sys.stdin.readline().rstrip('\n')
if int(res) % 1500 < 600 or int(res) % 1500 >= 900:
read_values_stack.extend(in_line.split(' '))
else:
read_values_stack.append(in_line)
raw_val = read_values_stack.pop(0)
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem
}
try:
if int(res) % 1500 < 300:
val = int(raw_val)
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, val)
elif int(res) % 1500 < 600:
val = float(raw_val)
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, val)
elif int(res) % 1500 < 900:
val = str(raw_val)
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, val)
elif int(res) % 1500 < 1200:
val = bool(raw_val)
memories[str(int(res) // 1500)].set_value_in_address(int(res) %
1500, val)
except Exception as e:
print(e)
def do_verify(_, right, res):
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem
}
res_dir_val = memories[str(int(res) // 1500)
].get_value_of_address(int(res) % 1500)
if res_dir_val < 0 or res_dir_val >= int(right):
raise IndexError('Index out of range')
def check_if_address(val):
if not '$' in val:
return val
local_mem = local_mems[-1]
temp_mem = temp_mems[-1]
memories = {
'0': global_mem,
'1': local_mem,
'2': temp_mem,
'3': constants_mem
}
return memories[str(int(val[1:]) // 1500)
].get_value_of_address(int(val[1:]) % 1500)
def run_quad(op, left, right, res):
global ip
operations = {
'+': do_addition,
'-': do_subtraction,
'*': do_multiplication,
'/': do_division,
'=': do_assignment,
'<': compare_lt,
'>': compare_gt,
'==': compare_eq,
'<>': compare_ne,
'<=': compare_leq,
'>=': compare_geq,
'|': do_or,
'&': do_and,
'goto': do_goto,
'goto_f': do_goto_f,
'print': do_print,
'read': do_read,
'gosub': do_gosub,
'era': do_era,
'param': do_param,
'end_func': do_endfunc,
'return': do_return,
'end': do_end,
'verify': do_verify
}
# print(ip, op, left, right, res)
if op != 'goto' and op != 'gosub' and op != 'verify' and op != 'end' and op != 'end_func' and op != 'era':
left = check_if_address(left)
right = check_if_address(right)
res = check_if_address(res)
try:
operations[op](left, right, res)
except Exception as e:
print(e)
exit(1)
if op != 'goto' and op != 'goto_f' and op != 'gosub':
ip += 1
if __name__ == '__main__':
filename = sys.argv[1]
with open(filename) as infile:
foo = infile.readline().split(' ')[2].split('\u001f')
ints, floats, strings, bools, _voids, *_ = foo
global_mem = Memory(ints, floats, strings, bools)
while True:
readline = infile.readline()
if readline == '#\n':
break
reconstruct_func_dir(readline)
ints, floats, strings, bools, * \
_ = func_dir['main']['num_types'].split('\u001f')
local_mems.append(Memory(ints, floats, strings, bools))
ints, floats, strings, bools, * \
_ = func_dir['main']['num_temps'].split('\u001f')
temp_mems.append(Memory(ints, floats, strings, bools))
while True:
readline = infile.readline()
if readline == '#\n':
break
class_name, num_types, *_ = readline.rstrip('\n').split(' ')
class_dir[class_name] = {'num_types': num_types}
while True:
readline = infile.readline()
if readline == '%\n':
break
reconstruct_class_dir(readline, class_name)
constants_mem = initialize_constant_mem(infile)
quads = infile.readlines()
while ip < len(quads):
op, left, right, res = quads[ip].rstrip('\n').split(' ')
run_quad(op, left, right, res)
|
#!/usr/bin/env python
"""General focus control.
To do: improve placement of countdown timer. Right now it works fine for Secondary Focus but probably not
for the NA2 Guider. But first see if the obs specs are comfortable with the NA2 Guider gmech controls.
History:
2008-02-04 ROwen
2008-02-11 ROwen Modified to always show the cancel button (now named X instead of Cancel).
2008-02-13 ROwen Fix PR 738: removed focus limits, since they were only a guess and getting it wrong
could put unreasonable limits on the user. Let the actor handle focus limits.
"""
import Tkinter
import RO.KeyVariable
import RO.Wdg
import RO.TkUtil
import RO.StringUtil
import TUI.TUIModel
MicronStr = RO.StringUtil.MuStr + "m"
class FocusWdg(Tkinter.Frame):
def __init__ (self,
master,
name,
statusBar = None,
increments = None,
defIncr = None,
helpURL = None,
label = "Focus",
formatStr = "%.1f",
units = MicronStr,
currLabel = "Focus",
focusWidth = 5,
buttonFrame = None,
**kargs):
"""A widget for displaying and specifying focus.
Subclasses must override createFocusCmd and must call startTimer, endTimer and updFocus
Inputs:
- master master Tk widget -- typically a frame or window
- name name of device whose focus is being adjusted; used for help
- statusBar an RO.Wdg.StatusBar widget
- increments focus increments (ints) for menu; defaults to 25, 50, 100
- defIncr default focus increment (int); defaults to increments[2]
- formatStr format for displaying focus
- units units of focus
- currLabel text for current focus label
- focusWidth width of focus input or output field
- buttonFrame button frame; if omitted then the buttons are shown right of the current focus
"""
Tkinter.Frame.__init__(self, master, **kargs)
if not increments:
increments = (25, 50, 100)
if not defIncr:
defIncr = int(increments[1])
self.name = str(name)
self.statusBar = statusBar
self.formatStr = formatStr
self.focusWidth = focusWidth
self.tuiModel = TUI.TUIModel.getModel()
self.currCmd = None
# current focus display
RO.Wdg.Label(self, text=currLabel).grid(row=0, column=0)
self.currFocusWdg = RO.Wdg.FloatLabel(
master = self,
formatStr = self.formatStr,
width = self.focusWidth,
helpText = "Current %s focus" % (self.name,),
helpURL = helpURL,
)
self.currFocusWdg.grid(row=0, column=1)
RO.Wdg.Label(self, text=units).grid(row=0, column=2)
self.timerWdg = RO.Wdg.TimeBar(
master = self,
autoStop = True,
helpText = "Estimated move time",
helpURL = helpURL,
)
self.timerWdg.grid(row=0, column=3, sticky="ew")
self.timerWdg.grid_remove()
self.grid_columnconfigure(3, weight=1)
# command buttons
if buttonFrame is None:
gridButtonFrame = True
buttonFrame = Tkinter.Frame(self)
else:
gridButtonFrame = False
col = 0
self.setButton = RO.Wdg.Button(
master = buttonFrame,
text = "Set...",
callFunc = self.doSet,
helpText = "Set %s focus" % (self.name,)
)
self.setButton.grid(row=0, column=col)
col += 1
self.decreaseButton = RO.Wdg.Button(
master=buttonFrame,
text = "-",
callFunc = self.doDeltaBtn,
helpURL = helpURL,
)
self.decreaseButton.grid(row=0, column=col)
col += 1
self.increaseButton = RO.Wdg.Button(
master=buttonFrame,
text = "+",
callFunc = self.doDeltaBtn,
helpURL = helpURL,
)
self.increaseButton.grid(row=0, column=col)
col += 1
incrStrs = ["%s %s" % (int(incr), units) for incr in increments]
defIncrStr = "%s %s" % (defIncr, units)
maxIncrLength = max([len(s) for s in incrStrs])
self.deltaMenu = RO.Wdg.OptionMenu(
master = buttonFrame,
items = incrStrs,
defValue = defIncrStr,
callFunc = self.doDeltaMenu,
width = maxIncrLength,
helpText = "Step size for -/+ buttons",
helpURL = helpURL,
)
self.deltaMenu.grid(row=0, column=col)
col += 1
self.cancelButton = RO.Wdg.Button(
master=buttonFrame,
text = "X",
callFunc = self.cmdCancel,
helpText = "Cancel focus command",
helpURL = helpURL,
)
self.cancelButton.grid(row=0, column=col)
col += 1
# allow button frame to grow on the right if necessary
buttonFrame.grid_columnconfigure(col, weight=1)
if gridButtonFrame:
buttonFrame.grid(row=0, column=4)
self.doDeltaMenu()
self.enableButtons()
def cmdCancel(self, cmd):
if self.currCmd:
self.currCmd.abort()
def cmdDone(self, *args, **kargs):
self.currCmd = None
self.enableButtons()
def doDeltaBtn(self, btn):
"""Called by the +/- buttons to offset the focus.
"""
deltaMagStr = self.deltaMenu.getString().split()[0]
deltaFocus = float(btn["text"] + deltaMagStr)
cmdVar = self.createFocusCmd(deltaFocus, isIncr=True)
self.runFocusCmd(cmdVar)
def doDeltaMenu(self, wdg=None):
"""Called by the focus increment menu to adjust the increment."""
incr = self.deltaMenu.getString()
self.decreaseButton.helpText = "Decrease %s focus by %s" % (self.name, incr)
self.increaseButton.helpText = "Increase %s focus by %s" % (self.name, incr)
def doSet(self, btn=None):
"""Called by the Set... button to set a new focus value."""
currFocus, isCurrent = self.currFocusWdg.get()
if isCurrent and currFocus is not None:
default = currFocus
else:
default = None
newFocus = FocusSetDialog(
master = self,
name = self.name,
initValue = default,
formatStr = self.formatStr,
focusWidth = self.focusWidth,
).result
if newFocus is None:
return
cmdVar = self.createFocusCmd(newFocus, isIncr=False)
self.runFocusCmd(cmdVar)
def startTimer(self, predTime, elapsedTime=0):
"""Display move timer."""
self.timerWdg.grid()
self.timerWdg.start(value=predTime, newMax = predTime)
def endTimer(self, dumValue=None, isCurrent=True, keyVar=None):
"""Hide move timer. May be a keyword variable callback."""
if isCurrent:
self.timerWdg.clear()
self.timerWdg.grid_remove()
def createFocusCmd(self, newFocus, isIncr=False):
"""Create and return a focus command.
This method must be subclassed.
"""
raise NotImplementedError("Subclass must define")
def enableButtons(self, wdg=None):
cmdRunning = self.currCmd and not self.currCmd.isDone()
self.setButton.setEnable(not cmdRunning)
self.decreaseButton.setEnable(not cmdRunning)
self.increaseButton.setEnable(not cmdRunning)
self.cancelButton.setEnable(cmdRunning)
def runFocusCmd(self, cmdVar):
"""Execute the focus command that was created by createFocusCmd"""
cmdVar.addCallback(
self.cmdDone,
callTypes = RO.KeyVariable.DoneTypes,
)
self.currCmd = cmdVar
self.statusBar.doCmd(cmdVar)
self.enableButtons()
def updFocus(self, newFocus, isCurrent=True, **kargs):
"""Called when new focus seen.
"""
self.currFocusWdg.set(newFocus, isCurrent=isCurrent)
class FocusSetDialog(RO.Wdg.ModalDialogBase):
def __init__(self, master, name, initValue, formatStr, focusWidth):
"""Create a new "set focus" dialog.
Inputs:
- name: name of focus item being set
- initValue: initial focus value
- formatStr: format for focus entry
- focusWidth: width of focus entry, in characters
"""
self.name = name
if initValue is None:
initValue = 0
self.initValue = float(initValue)
self.formatStr = formatStr
self.focusWidth = int(focusWidth)
RO.Wdg.ModalDialogBase.__init__(self,
master,
title="Set Focus",
)
def body(self, master):
l = Tkinter.Label(master, text="New %s Focus:" % (self.name,))
l.pack(side="top", anchor="w")
valFrame = Tkinter.Frame(master)
self.valWdg = RO.Wdg.FloatEntry(valFrame,
defValue = self.initValue,
defFormat = self.formatStr,
width = self.focusWidth,
defMenu = "Default",
helpText = "%s focus offset" % (self.name,),
)
if RO.TkUtil.getWindowingSystem() == RO.TkUtil.WSysAqua:
# work around tk bug 1101854
self.valWdg.unbind("<<CtxMenu>>")
self.valWdg.selectAll()
self.valWdg.pack(side="left")
u = Tkinter.Label(valFrame,
text=RO.StringUtil.MuStr + "m",
)
u.pack(side="left")
valFrame.pack(side="top", anchor="w")
# s = RO.Wdg.StatusBar(master)
# s.pack(side="top", expand=True, fill="x")
self.okWdg.helpText = "Set %s focus" % (self.name.lower(),)
self.cancelWdg.helpText = "Cancel"
return self.valWdg
def setResult(self):
self.result = self.valWdg.getNumOrNone()
if __name__ == "__main__":
root = RO.Wdg.PythonTk()
class TestFocusWdg(FocusWdg):
def __init__(self, master, statusBar):
FocusWdg.__init__(self,
master,
name = "test",
statusBar = statusBar,
increments = (25, 50, 100),
defIncr = 50,
helpURL = None,
label = "Focus",
)
def createFocusCmd(self, newFocus, isIncr=False):
if isIncr:
verbStr = "relfocus"
else:
verbStr = "focus"
cmdStr = "%s=%s" % (verbStr, newFocus)
return RO.KeyVariable.CmdVar (
actor = "test",
cmdStr = cmdStr,
)
tuiModel = TUI.TUIModel.getModel(True)
kd = tuiModel.dispatcher
statusBar = RO.Wdg.StatusBar(
master = root,
dispatcher = tuiModel.dispatcher,
prefs = tuiModel.prefs,
playCmdSounds = True,
)
sfw = TestFocusWdg(root, statusBar = statusBar)
sfw.pack()
statusBar.pack(expand=True, fill="x")
root.mainloop()
|
import dataiku
from dataiku.customrecipe import (
get_recipe_config,
get_input_names_for_role,
get_output_names_for_role,
)
import re
from gluonts.time_feature import get_seasonality
from gluonts_forecasts.model_config_registry import ModelConfigRegistry
from dku_io_utils.partitions_handling import get_folder_partition_root, check_only_one_read_partition
from dku_constants import FORECASTING_STYLE_PRESELECTED_MODELS, GPU_CONFIGURATION, DEFAULT_SEASONALITIES
from safe_logger import SafeLogger
logger = SafeLogger("Forecast plugin")
class PluginParamValidationError(ValueError):
"""Custom exception raised when the the plugin parameters chosen by the user are invalid"""
pass
def load_training_config(recipe_config):
"""Utility function to load, resolve and validate all training recipe config into a clean `params` dictionary
Returns:
Dictionary of parameter names (key) and values
"""
params = {}
input_dataset_name = get_input_names_for_role("input_dataset")[0]
params["training_dataset"] = dataiku.Dataset(input_dataset_name)
training_dataset_columns = [p["name"] for p in params["training_dataset"].read_schema()]
model_folder_name = get_output_names_for_role("model_folder")[0]
params["model_folder"] = dataiku.Folder(model_folder_name)
params["partition_root"] = get_folder_partition_root(params["model_folder"])
check_only_one_read_partition(params["partition_root"], params["training_dataset"])
evaluation_dataset_name = get_output_names_for_role("evaluation_dataset")[0]
params["evaluation_dataset"] = dataiku.Dataset(evaluation_dataset_name)
params["make_forecasts"] = False
evaluation_forecasts_dataset_names = get_output_names_for_role("evaluation_forecasts_dataset")
if len(evaluation_forecasts_dataset_names) > 0:
params["evaluation_forecasts_dataset"] = dataiku.Dataset(evaluation_forecasts_dataset_names[0])
params["make_forecasts"] = True
params["time_column_name"] = recipe_config.get("time_column")
if params["time_column_name"] is None:
raise PluginParamValidationError("Time column is mandatory:, please select one")
elif params["time_column_name"] not in training_dataset_columns:
raise PluginParamValidationError(f"Invalid time column selection: {params['time_column_name']}")
params["target_columns_names"] = sanitize_column_list(recipe_config.get("target_columns"))
if len(params["target_columns_names"]) == 0 or not all(
column in training_dataset_columns for column in params["target_columns_names"]
):
raise PluginParamValidationError(f"Invalid target column(s) selection: {params['target_columns_names']}")
params["target_columns_names"] = reorder_column_list(params["target_columns_names"], training_dataset_columns)
long_format = recipe_config.get("additional_columns", False)
if long_format:
params["timeseries_identifiers_names"] = sanitize_column_list(recipe_config.get("timeseries_identifiers", []))
if not all(column in training_dataset_columns for column in params["timeseries_identifiers_names"]):
raise PluginParamValidationError(
f"Invalid time series identifiers selection: {params['timeseries_identifiers_names']}"
)
else:
params["timeseries_identifiers_names"] = []
params["is_training_multivariate"] = (
True
if (len(params["target_columns_names"]) > 1) or (len(params["timeseries_identifiers_names"]) > 0)
else False
)
if long_format and len(params["timeseries_identifiers_names"]) == 0:
raise PluginParamValidationError("Long format is activated but no time series identifiers have been provided")
external_feature_activated = recipe_config.get("external_feature_activated", False)
if external_feature_activated:
params["external_features_columns_names"] = sanitize_column_list(
recipe_config.get("external_feature_columns", [])
)
else:
params["external_features_columns_names"] = []
if not all(column in training_dataset_columns for column in params["external_features_columns_names"]):
raise PluginParamValidationError(
f"Invalid external features selection: {params['external_features_columns_names']}"
)
params["frequency_unit"] = recipe_config.get("frequency_unit")
if params["frequency_unit"] == "W":
params["frequency"] = f"W-{recipe_config.get('frequency_end_of_week', 'SUN')}"
elif params["frequency_unit"] == "H":
params["frequency"] = f"{recipe_config.get('frequency_step_hours', 1)}H"
elif params["frequency_unit"] == "min":
params["frequency"] = f"{recipe_config.get('frequency_step_minutes', 1)}min"
else:
params["frequency"] = params["frequency_unit"]
params["prediction_length"] = recipe_config.get("prediction_length")
if not params["prediction_length"]:
raise PluginParamValidationError("Please specify forecasting horizon")
params["season_length"] = recipe_config.get(f"season_length_{params['frequency_unit']}", 1)
if params["season_length"] < 1:
raise PluginParamValidationError("Seasonality must be higher than 1")
params["use_gpu"] = recipe_config.get("use_gpu", False)
if params["use_gpu"]:
params["gpu_location"] = recipe_config.get("gpu_location", "local_gpu")
if params["gpu_location"] == "local_gpu":
gpu_devices = recipe_config.get("gpu_devices", [])
params["gpu_devices"] = parse_gpu_devices(gpu_devices)
else:
params["gpu_devices"] = [GPU_CONFIGURATION.CONTAINER_GPU]
else:
params["gpu_devices"] = None
params["forecasting_style"] = recipe_config.get("forecasting_style", "auto")
params["epoch"] = recipe_config.get("epoch", 10)
params["batch_size"] = recipe_config.get("batch_size", 32)
params["auto_num_batches_per_epoch"] = recipe_config.get("auto_num_batches_per_epoch", True)
if params["auto_num_batches_per_epoch"]:
params["num_batches_per_epoch"] = -1
else:
params["num_batches_per_epoch"] = recipe_config.get("num_batches_per_epoch", 50)
if params["num_batches_per_epoch"] == 0:
raise PluginParamValidationError("Number of batches per epoch cannot be 0")
# Overwrite values in case of autoML mode selected
params = automl_params_overwrite(params)
params["sampling_method"] = recipe_config.get("sampling_method", "last_records")
params["max_timeseries_length"] = None
if params["sampling_method"] == "last_records":
params["max_timeseries_length"] = recipe_config.get("number_records", 10000)
if params["max_timeseries_length"] < 4:
raise PluginParamValidationError("Number of records must be higher than 4")
params["evaluation_strategy"] = "split"
params["evaluation_only"] = False
printable_params = {
param: value for param, value in params.items() if "dataset" not in param and "folder" not in param
}
logger.info(f"Recipe parameters: {printable_params}")
return params
def load_predict_config():
"""Utility function to load, resolve and validate all predict recipe config into a clean `params` dictionary
Returns:
Dictionary of parameter names (key) and values
"""
params = {}
recipe_config = get_recipe_config()
# model folder
model_folder = dataiku.Folder(get_input_names_for_role("model_folder")[0])
params["model_folder"] = model_folder
params["partition_root"] = get_folder_partition_root(params["model_folder"], is_input=True)
params["external_features_future_dataset"] = None
external_features_future_dataset_names = get_input_names_for_role("external_features_future_dataset")
if len(external_features_future_dataset_names) > 0:
params["external_features_future_dataset"] = dataiku.Dataset(external_features_future_dataset_names[0])
# output dataset
output_dataset_names = get_output_names_for_role("output_dataset")
if len(output_dataset_names) == 0:
raise PluginParamValidationError("Please specify Forecast dataset in the 'Input / Output' tab of the recipe")
params["output_dataset"] = dataiku.Dataset(output_dataset_names[0])
check_only_one_read_partition(params["partition_root"], params["model_folder"])
check_only_one_read_partition(params["partition_root"], params["external_features_future_dataset"])
params["manual_selection"] = True if recipe_config.get("model_selection_mode") == "manual" else False
params["performance_metric"] = recipe_config.get("performance_metric")
params["selected_session"] = recipe_config.get("manually_selected_session", "latest_session")
params["selected_model_label"] = recipe_config.get("manually_selected_model_label")
params["prediction_length"] = recipe_config.get("prediction_length", -1)
params["confidence_interval"] = recipe_config.get("confidence_interval", 95)
params["quantiles"] = convert_confidence_interval_to_quantiles(params["confidence_interval"])
params["include_history"] = recipe_config.get("include_history", False)
params["sampling_method"] = recipe_config.get("sampling_method", "last_records")
params["history_length_limit"] = None
if params["sampling_method"] == "last_records":
params["history_length_limit"] = recipe_config.get("number_records", 1000)
if params["history_length_limit"] < 1:
raise PluginParamValidationError("Number of historical records must be higher than 1")
printable_params = {
param: value for param, value in params.items() if "dataset" not in param and "folder" not in param
}
logger.info(f"Recipe parameters: {printable_params}")
return params
def get_models_parameters(config, is_training_multivariate=False):
"""Create a models parameters dictionary to store for each activated model its parameters (activated, kwargs, ...)
Args:
config (dict): Recipe config dictionary obtained with dataiku.customrecipe.get_recipe_config().
Raises:
ValueError: If a prediction_length parameter is trying to be set in the model params.
Returns:
Dictionary of model parameter (value) by activated model name (key).
"""
models_parameters = {}
for model in ModelConfigRegistry().list_available_models():
if is_activated(config, model, is_training_multivariate):
model_presets = get_model_presets(config, model)
if "prediction_length" in model_presets.get("kwargs", {}):
raise ValueError(
"Keyword argument 'prediction_length' is not writable, please use the Forecasting horizon parameter"
)
models_parameters.update({model: model_presets})
if not models_parameters:
raise PluginParamValidationError("Please select at least one model")
logger.info(f"Model parameters: {models_parameters}")
return models_parameters
def is_activated(config, model, is_training_multivariate=False):
"""Returns the activation status for a model according to the selected forcasting style (auto / auto_performance) or UX config otherwise.
Args:
config (dict): Recipe config dictionary obtained with dataiku.customrecipe.get_recipe_config().
model (str): Model name found in the UI.
Returns:
True if model is activated, else False.
"""
forecasting_style = config.get("forecasting_style", "auto") + (
"_multivariate" if is_training_multivariate else "_univariate"
)
if forecasting_style in FORECASTING_STYLE_PRESELECTED_MODELS:
preselected_models = FORECASTING_STYLE_PRESELECTED_MODELS.get(forecasting_style)
return model in preselected_models
return config.get(f"{model}_model_activated", False)
def get_model_presets(config, model):
"""Collect all the parameters model from the UI and return them as a dict.
Args:
config (dict): Recipe config dictionary obtained with dataiku.customrecipe.get_recipe_config().
model (str): Model name found in the UI.
Returns:
Dictionary of model parameters to be used as kwargs in gluonts Predictor.
"""
model_presets = {}
matching_key = f"{model}_model_(.*)"
for key in config:
key_search = re.match(matching_key, key, re.IGNORECASE)
if key_search:
key_type = key_search.group(1)
model_presets.update({key_type: config[key]})
return model_presets
def automl_params_overwrite(params):
"""Overwrite some training options based on the selected automl mode"""
params_copy = params.copy()
if params_copy["forecasting_style"].startswith("auto"):
params_copy["season_length"] = get_seasonality(params_copy["frequency"], DEFAULT_SEASONALITIES)
params_copy["batch_size"] = 128 if params_copy["use_gpu"] else 32
if params_copy["forecasting_style"] == "auto":
params_copy["epoch"] = 10
params_copy["num_batches_per_epoch"] = 50
elif params_copy["forecasting_style"] == "auto_performance":
params_copy["context_length"] = params_copy["prediction_length"]
params_copy["epoch"] = 30 if params_copy["is_training_multivariate"] else 10
params_copy["num_batches_per_epoch"] = -1
return params_copy
def sanitize_column_list(input_column_list):
"""Remove empty elements (Nones, '') from input columns list"""
sanitized_column_list = [input for input in input_column_list if input]
return sanitized_column_list
def convert_confidence_interval_to_quantiles(confidence_interval):
"""Convert a confidence interval value into a list of lower and upper quantiles with also the median.
Args:
confidence_interval (int): Percentage.
Raises:
PluginParamValidationError: If the selected confidence interval is not between 1 and 99.
Returns:
List of quantiles.
"""
if confidence_interval < 1 or confidence_interval > 99:
raise PluginParamValidationError("Please choose a confidence interval between 1 and 99.")
alpha = (100 - confidence_interval) / 2 / 100.0
quantiles = [round(alpha, 3), 0.5, round(1 - alpha, 3)]
return quantiles
def reorder_column_list(column_list_to_reorder, reference_column_list):
"""Keep the target list in same order as the training dataset, for consistency of forecasted columns order"""
reordered_list = []
for column_name in reference_column_list:
if column_name in column_list_to_reorder:
reordered_list.append(column_name)
return reordered_list
def parse_gpu_devices(gpu_devices):
"""Check the custom python MULTISELECT for GPU devices
Args:
gpu_devices (list): List of GPU number or ["no_gpu"]
Raises:
PluginParamValidationError:
If more than 1 GPU are selected (for now we support only one GPU)
If selected value is "no_gpu"
Returns:
List of a single GPU (we may support multiple later) or None
"""
if len(gpu_devices) == 0: # nothing selected
raise PluginParamValidationError("Please select one local GPU device")
elif len(gpu_devices) > 1:
raise PluginParamValidationError(
"GluonTS does not currently support multi-GPU training, please select only one GPU device"
)
else: # one element list
if gpu_devices[0] == GPU_CONFIGURATION.NO_GPU:
raise PluginParamValidationError(
"Local GPU device parameter is invalid, please check the CUDA/GPU installation on the DSS server"
)
else:
return [int(gpu_device.split("_")[1]) for gpu_device in gpu_devices]
|
# Copyright 2022 The Casdoor Authors. All Rights Reserved.
#
# 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.
from casdoor import CasdoorSDK
from flask import jsonify, redirect, current_app, request, session, make_response, render_template
from flask_restful import Resource, reqparse
from .utils import authz_required
class SignIn(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('code', required=True)
parser.add_argument('state', required=True)
args = parser.parse_args()
code = args['code']
state = args['state']
sdk: CasdoorSDK = current_app.config.get('CASDOOR_SDK')
token = sdk.get_oauth_token(code)
user = sdk.parse_jwt_token(token)
session['casdoorUser'] = user
return jsonify({'status': 'ok'})
class SignOut(Resource):
@authz_required
def post(self):
del session['casdoorUser']
return jsonify({
'status': 'ok'
})
class ToLogin(Resource):
def get(self):
sdk: CasdoorSDK = current_app.config.get('CASDOOR_SDK')
redirect_url = sdk.get_auth_link(redirect_uri=current_app.config.get('REDIRECT_URI'), state='app-built-in')
return make_response(render_template('tologin.html', redirect_url=redirect_url))
|
// Copyright (C) 2013 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 19.4.3.1
description: >
Symbol constructor
features: [Symbol]
---*/
assert.sameValue(
Object.getPrototypeOf(Symbol('66')).constructor,
Symbol,
"The value of `Object.getPrototypeOf(Symbol('66')).constructor` is `Symbol`"
);
assert.sameValue(
Object.getPrototypeOf(Object(Symbol('66'))).constructor,
Symbol,
"The value of `Object.getPrototypeOf(Object(Symbol('66'))).constructor` is `Symbol`"
);
|
import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { listProducts } from '../actions/prodList'
import { ProductCards } from '../components/ProductCards'
const Home = () => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(listProducts())
}, [dispatch])
return (
<div className="home">
<div className="home__container">
{/* <img
className="home__image"
src="https://images-eu.ssl-images-amazon.com/images/G/02/digital/video/merch2016/Hero/Covid19/Generic/GWBleedingHero_ENG_COVIDUPDATE__XSite_1500x600_PV_en-GB._CB428684220_.jpg"
alt=""
/> */}
</div>
<section>
<ProductCards />
</section>
</div>
)
}
export default Home
|
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var index = require('./routes/index');
var project = require('./routes/project');
var hello = require('./routes/hello');
// Example route
// var user = require('./routes/user');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('IxD secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// Add routes here
app.get('/', index.view);
app.get('/hello/:userName', hello.view);
// Example route
// app.get('/users', user.list);
app.get('/project', project.viewProject);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.