text
stringlengths
7
3.69M
import { isLoggedIn, getToken } from './auth'; export const isOwner = (username) => { if (isLoggedIn()) { return username === getToken().username; } return false; }; export default isOwner;
if(typeof (dojo)!="undefined"){ dojo.provide("Freja"); } if(typeof (Freja)=="undefined"){ Freja={}; } Freja.NAME="Freja"; Freja.VERSION="2.1.2"; Freja.__repr__=function(){ return "["+this.NAME+" "+this.VERSION+"]"; }; Freja.toString=function(){ return this.__repr__(); }; Freja.Class={}; Freja.Class.extend=function(_1,_2){ var _3=function(){ }; _3.prototype=_2.prototype; _1.prototype=new _3(); _1.prototype.constructor=_1; _1.prototype.superconstructor=_2; _1.prototype.supertype=_2.prototype; }; if(typeof (dojo)!="undefined"){ dojo.require("MochiKit.Base"); dojo.require("MochiKit.Signal"); dojo.require("MochiKit.Async"); dojo.require("Sarissa"); } if(typeof (JSAN)!="undefined"){ JSAN.use("MochiKit.Base",[]); JSAN.use("MochiKit.Signal",[]); JSAN.use("MochiKit.Async",[]); JSAN.use("Sarissa",[]); } try{ if(typeof (MochiKit.Base)=="undefined"){ throw ""; } if(typeof (MochiKit.Signal)=="undefined"){ throw ""; } if(typeof (MochiKit.Async)=="undefined"){ throw ""; } if(typeof (Sarissa)=="undefined"){ throw ""; } } catch(e){ throw new Error("Freja depends on MochiKit.Base, MochiKit.Signal, MochiKit.Async and Sarissa!"); } if(typeof (Freja)=="undefined"){ Freja={}; } Freja._aux={}; Freja._aux.bind=MochiKit.Base.bind; Freja._aux.formContents=function(_4){ if(!_4){ _4=document; } var _5=[]; var _6=[]; var _7=_4.getElementsByTagName("INPUT"); for(var i=0;i<_7.length;++i){ var _9=_7[i]; if(_9.name){ if(_9.type=="radio"||_9.type=="checkbox"){ if(_9.checked){ _5.push(_9.name); _6.push(_9.value); }else{ _5.push(_9.name); _6.push(""); } }else{ _5.push(_9.name); _6.push(_9.value); } } } var _a=_4.getElementsByTagName("TEXTAREA"); for(var i=0;i<_a.length;++i){ var _9=_a[i]; if(_9.name){ _5.push(_9.name); _6.push(_9.value); } } var _b=_4.getElementsByTagName("SELECT"); for(var i=0;i<_b.length;++i){ var _9=_b[i]; if(_9.name){ if(_9.selectedIndex>=0){ var _c=_9.options[_9.selectedIndex]; _5.push(_9.name); _6.push((_c.value)?_c.value:""); } } } return [_5,_6]; }; Freja._aux.getElement=MochiKit.DOM.getElement; Freja._aux.connect=MochiKit.Signal.connect; Freja._aux.signal=MochiKit.Signal.signal; Freja._aux.createDeferred=function(){ return new MochiKit.Async.Deferred(); }; Freja._aux.openXMLHttpRequest=function(_d,_e,_f,_10,_11){ var req=new XMLHttpRequest(); if(_10&&_11){ req.open(_d,_e,_f,_10,_11); }else{ req.open(_d,_e,_f); } if(_d=="POST"||_d=="PUT"){ req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); } req.setRequestHeader("X-Requested-With","XMLHttpRequest"); return req; }; Freja._aux.sendXMLHttpRequest=MochiKit.Async.sendXMLHttpRequest; Freja._aux.xmlize=Sarissa.xmlize; Freja._aux.serializeXML=function(_13){ if(_13.xml){ return _13.xml; } return (new XMLSerializer()).serializeToString(_13); }; Freja._aux.loadXML=function(_14){ return (new DOMParser()).parseFromString(_14,"text/xml"); }; Freja._aux.transformXSL=function(xml,xsl,_17){ var _18=new XSLTProcessor(); _18.importStylesheet(xsl); if(_17){ for(var _19 in _17){ _18.setParameter("",_19,_17[_19]); } } return _18.transformToFragment(xml,window.document); }; Freja._aux.cloneXMLDocument=function(_1a){ var _1b=null; try{ _1b=_1a.cloneNode(true); } catch(e){ } if(!_1b){ if(document.implementation&&document.implementation.createDocument){ _1b=document.implementation.createDocument("",_1a.documentElement.nodeName,null); var _1c=_1b.importNode(_1a.documentElement.cloneNode(true),true); try{ _1b.appendChild(_1c); } catch(e){ var _1d=_1b.documentElement; for(var i=_1c.childNodes.length-1;i>=0;i--){ _1d.insertBefore(_1c.childNodes[i],_1d.firstChild); } for(var i=0;i<_1a.documentElement.attributes.length;i++){ var _1f=_1a.documentElement.attributes.item(i).name; var _20=_1a.documentElement.attributes.item(i).value; _1b.documentElement.setAttribute(_1f,_20); } } } } return _1b; }; Freja._aux.hasSupportForXSLT=function(){ return (typeof (XSLTProcessor)!="undefined"); }; Freja._aux.createQueryEngine=function(){ if(Sarissa._SARISSA_IS_IE||Sarissa.IS_ENABLED_SELECT_NODES){ return new Freja.QueryEngine.XPath(); }else{ return new Freja.QueryEngine.SimplePath(); } }; Freja._aux.importNode=function(_21,_22,_23){ if(typeof _23=="undefined"){ _23=true; } if(_21.importNode){ return _21.importNode(_22,_23); }else{ return _22.cloneNode(_23); } }; function Sarissa(){ } Sarissa.VERSION="0.9.9.4"; Sarissa.PARSED_OK="Document contains no parsing errors"; Sarissa.PARSED_EMPTY="Document is empty"; Sarissa.PARSED_UNKNOWN_ERROR="Not well-formed or other error"; Sarissa.IS_ENABLED_TRANSFORM_NODE=false; Sarissa.REMOTE_CALL_FLAG="gr.abiss.sarissa.REMOTE_CALL_FLAG"; Sarissa._lastUniqueSuffix=0; Sarissa._getUniqueSuffix=function(){ return Sarissa._lastUniqueSuffix++; }; Sarissa._SARISSA_IEPREFIX4XSLPARAM=""; Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION=document.implementation&&true; Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT=Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION&&document.implementation.createDocument; Sarissa._SARISSA_HAS_DOM_FEATURE=Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION&&document.implementation.hasFeature; Sarissa._SARISSA_IS_MOZ=Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT&&Sarissa._SARISSA_HAS_DOM_FEATURE; Sarissa._SARISSA_IS_SAFARI=navigator.userAgent.toLowerCase().indexOf("safari")!=-1||navigator.userAgent.toLowerCase().indexOf("konqueror")!=-1; Sarissa._SARISSA_IS_SAFARI_OLD=Sarissa._SARISSA_IS_SAFARI&&(parseInt((navigator.userAgent.match(/AppleWebKit\/(\d+)/)||{})[1],10)<420); Sarissa._SARISSA_IS_IE=document.all&&window.ActiveXObject&&navigator.userAgent.toLowerCase().indexOf("msie")>-1&&navigator.userAgent.toLowerCase().indexOf("opera")==-1; Sarissa._SARISSA_IS_OPERA=navigator.userAgent.toLowerCase().indexOf("opera")!=-1; if(!window.Node||!Node.ELEMENT_NODE){ Node={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12}; } if(Sarissa._SARISSA_IS_SAFARI_OLD){ HTMLHtmlElement=document.createElement("html").constructor; Node=HTMLElement={}; HTMLElement.prototype=HTMLHtmlElement.__proto__.__proto__; HTMLDocument=Document=document.constructor; var x=new DOMParser(); XMLDocument=x.constructor; Element=x.parseFromString("<Single />","text/xml").documentElement.constructor; x=null; } if(typeof XMLDocument=="undefined"&&typeof Document!="undefined"){ XMLDocument=Document; } if(Sarissa._SARISSA_IS_IE){ Sarissa._SARISSA_IEPREFIX4XSLPARAM="xsl:"; var _SARISSA_DOM_PROGID=""; var _SARISSA_XMLHTTP_PROGID=""; var _SARISSA_DOM_XMLWRITER=""; Sarissa.pickRecentProgID=function(_24){ var _25=false,e; var _26; for(var i=0;i<_24.length&&!_25;i++){ try{ var _28=new ActiveXObject(_24[i]); _26=_24[i]; _25=true; } catch(objException){ e=objException; } } if(!_25){ throw "Could not retrieve a valid progID of Class: "+_24[_24.length-1]+". (original exception: "+e+")"; } _24=null; return _26; }; _SARISSA_DOM_PROGID=null; _SARISSA_THREADEDDOM_PROGID=null; _SARISSA_XSLTEMPLATE_PROGID=null; _SARISSA_XMLHTTP_PROGID=null; XMLHttpRequest=function(){ if(!_SARISSA_XMLHTTP_PROGID){ _SARISSA_XMLHTTP_PROGID=Sarissa.pickRecentProgID(["Msxml2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"]); } return new ActiveXObject(_SARISSA_XMLHTTP_PROGID); }; Sarissa.getDomDocument=function(_29,_2a){ if(!_SARISSA_DOM_PROGID){ _SARISSA_DOM_PROGID=Sarissa.pickRecentProgID(["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.3.0","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"]); } var _2b=new ActiveXObject(_SARISSA_DOM_PROGID); if(_2a){ var _2c=""; if(_29){ if(_2a.indexOf(":")>1){ _2c=_2a.substring(0,_2a.indexOf(":")); _2a=_2a.substring(_2a.indexOf(":")+1); }else{ _2c="a"+Sarissa._getUniqueSuffix(); } } if(_29){ _2b.loadXML("<"+_2c+":"+_2a+" xmlns:"+_2c+"=\""+_29+"\""+" />"); }else{ _2b.loadXML("<"+_2a+" />"); } } return _2b; }; Sarissa.getParseErrorText=function(_2d){ var _2e=Sarissa.PARSED_OK; if(_2d&&_2d.parseError&&_2d.parseError.errorCode&&_2d.parseError.errorCode!=0){ _2e="XML Parsing Error: "+_2d.parseError.reason+"\nLocation: "+_2d.parseError.url+"\nLine Number "+_2d.parseError.line+", Column "+_2d.parseError.linepos+":\n"+_2d.parseError.srcText+"\n"; for(var i=0;i<_2d.parseError.linepos;i++){ _2e+="-"; } _2e+="^\n"; }else{ if(_2d.documentElement===null){ _2e=Sarissa.PARSED_EMPTY; } } return _2e; }; Sarissa.setXpathNamespaces=function(_30,_31){ _30.setProperty("SelectionLanguage","XPath"); _30.setProperty("SelectionNamespaces",_31); }; XSLTProcessor=function(){ if(!_SARISSA_XSLTEMPLATE_PROGID){ _SARISSA_XSLTEMPLATE_PROGID=Sarissa.pickRecentProgID(["Msxml2.XSLTemplate.6.0","MSXML2.XSLTemplate.3.0"]); } this.template=new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID); this.processor=null; }; XSLTProcessor.prototype.importStylesheet=function(_32){ if(!_SARISSA_THREADEDDOM_PROGID){ _SARISSA_THREADEDDOM_PROGID=Sarissa.pickRecentProgID(["MSXML2.FreeThreadedDOMDocument.6.0","MSXML2.FreeThreadedDOMDocument.3.0"]); } _32.setProperty("SelectionLanguage","XPath"); _32.setProperty("SelectionNamespaces","xmlns:xsl='http://www.w3.org/1999/XSL/Transform'"); var _33=new ActiveXObject(_SARISSA_THREADEDDOM_PROGID); try{ _33.resolveExternals=true; _33.setProperty("AllowDocumentFunction",true); } catch(e){ } if(_32.url&&_32.selectSingleNode("//xsl:*[local-name() = 'import' or local-name() = 'include']")!=null){ _33.async=false; _33.load(_32.url); }else{ _33.loadXML(_32.xml); } _33.setProperty("SelectionNamespaces","xmlns:xsl='http://www.w3.org/1999/XSL/Transform'"); var _34=_33.selectSingleNode("//xsl:output"); if(_34){ this.outputMethod=_34.getAttribute("method"); }else{ delete this.outputMethod; } this.template.stylesheet=_33; this.processor=this.template.createProcessor(); this.paramsSet=[]; }; XSLTProcessor.prototype.transformToDocument=function(_35){ var _36; if(_SARISSA_THREADEDDOM_PROGID){ this.processor.input=_35; _36=new ActiveXObject(_SARISSA_DOM_PROGID); this.processor.output=_36; this.processor.transform(); return _36; }else{ if(!_SARISSA_DOM_XMLWRITER){ _SARISSA_DOM_XMLWRITER=Sarissa.pickRecentProgID(["Msxml2.MXXMLWriter.6.0","Msxml2.MXXMLWriter.3.0","MSXML2.MXXMLWriter","MSXML.MXXMLWriter","Microsoft.XMLDOM"]); } this.processor.input=_35; _36=new ActiveXObject(_SARISSA_DOM_XMLWRITER); this.processor.output=_36; this.processor.transform(); var _37=new ActiveXObject(_SARISSA_DOM_PROGID); _37.loadXML(_36.output+""); return _37; } }; XSLTProcessor.prototype.transformToFragment=function(_38,_39){ this.processor.input=_38; this.processor.transform(); var s=this.processor.output; var f=_39.createDocumentFragment(); var _3c; if(this.outputMethod=="text"){ f.appendChild(_39.createTextNode(s)); }else{ if(_39.body&&_39.body.innerHTML){ _3c=_39.createElement("div"); _3c.innerHTML=s; while(_3c.hasChildNodes()){ f.appendChild(_3c.firstChild); } }else{ var _3d=new ActiveXObject(_SARISSA_DOM_PROGID); if(s.substring(0,5)=="<?xml"){ s=s.substring(s.indexOf("?>")+2); } var xml="".concat("<my>",s,"</my>"); _3d.loadXML(xml); _3c=_3d.documentElement; while(_3c.hasChildNodes()){ f.appendChild(_3c.firstChild); } } } return f; }; XSLTProcessor.prototype.setParameter=function(_3f,_40,_41){ _41=_41?_41:""; if(_3f){ this.processor.addParameter(_40,_41,_3f); }else{ this.processor.addParameter(_40,_41); } _3f=""+(_3f||""); if(!this.paramsSet[_3f]){ this.paramsSet[_3f]=[]; } this.paramsSet[_3f][_40]=_41; }; XSLTProcessor.prototype.getParameter=function(_42,_43){ _42=""+(_42||""); if(this.paramsSet[_42]&&this.paramsSet[_42][_43]){ return this.paramsSet[_42][_43]; }else{ return null; } }; XSLTProcessor.prototype.clearParameters=function(){ for(var _44 in this.paramsSet){ for(var _45 in this.paramsSet[_44]){ if(_44!=""){ this.processor.addParameter(_45,"",_44); }else{ this.processor.addParameter(_45,""); } } } this.paramsSet=[]; }; }else{ if(Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT){ Sarissa.__handleLoad__=function(_46){ Sarissa.__setReadyState__(_46,4); }; _sarissa_XMLDocument_onload=function(){ Sarissa.__handleLoad__(this); }; Sarissa.__setReadyState__=function(_47,_48){ _47.readyState=_48; _47.readystate=_48; if(_47.onreadystatechange!=null&&typeof _47.onreadystatechange=="function"){ _47.onreadystatechange(); } }; Sarissa.getDomDocument=function(_49,_4a){ var _4b=document.implementation.createDocument(_49?_49:null,_4a?_4a:null,null); if(!_4b.onreadystatechange){ _4b.onreadystatechange=null; } if(!_4b.readyState){ _4b.readyState=0; } _4b.addEventListener("load",_sarissa_XMLDocument_onload,false); return _4b; }; if(window.XMLDocument){ }else{ if(Sarissa._SARISSA_HAS_DOM_FEATURE&&window.Document&&!Document.prototype.load&&document.implementation.hasFeature("LS","3.0")){ Sarissa.getDomDocument=function(_4c,_4d){ var _4e=document.implementation.createDocument(_4c?_4c:null,_4d?_4d:null,null); return _4e; }; }else{ Sarissa.getDomDocument=function(_4f,_50){ var _51=document.implementation.createDocument(_4f?_4f:null,_50?_50:null,null); if(_51&&(_4f||_50)&&!_51.documentElement){ _51.appendChild(_51.createElementNS(_4f,_50)); } return _51; }; } } } } if(!window.DOMParser){ if(Sarissa._SARISSA_IS_SAFARI){ DOMParser=function(){ }; DOMParser.prototype.parseFromString=function(_52,_53){ var _54=new XMLHttpRequest(); _54.open("GET","data:text/xml;charset=utf-8,"+encodeURIComponent(_52),false); _54.send(null); return _54.responseXML; }; }else{ if(Sarissa.getDomDocument&&Sarissa.getDomDocument()&&Sarissa.getDomDocument(null,"bar").xml){ DOMParser=function(){ }; DOMParser.prototype.parseFromString=function(_55,_56){ var doc=Sarissa.getDomDocument(); doc.loadXML(_55); return doc; }; } } } if((typeof (document.importNode)=="undefined")&&Sarissa._SARISSA_IS_IE){ try{ document.importNode=function(_58,_59){ var tmp; if(_58.nodeName=="#text"){ return document.createTextNode(_58.data); }else{ if(_58.nodeName=="tbody"||_58.nodeName=="tr"){ tmp=document.createElement("table"); }else{ if(_58.nodeName=="td"){ tmp=document.createElement("tr"); }else{ if(_58.nodeName=="option"){ tmp=document.createElement("select"); }else{ tmp=document.createElement("div"); } } } if(_59){ tmp.innerHTML=_58.xml?_58.xml:_58.outerHTML; }else{ tmp.innerHTML=_58.xml?_58.cloneNode(false).xml:_58.cloneNode(false).outerHTML; } return tmp.getElementsByTagName("*")[0]; } }; } catch(e){ } } if(!Sarissa.getParseErrorText){ Sarissa.getParseErrorText=function(_5b){ var _5c=Sarissa.PARSED_OK; if((!_5b)||(!_5b.documentElement)){ _5c=Sarissa.PARSED_EMPTY; }else{ if(_5b.documentElement.tagName=="parsererror"){ _5c=_5b.documentElement.firstChild.data; _5c+="\n"+_5b.documentElement.firstChild.nextSibling.firstChild.data; }else{ if(_5b.getElementsByTagName("parsererror").length>0){ var _5d=_5b.getElementsByTagName("parsererror")[0]; _5c=Sarissa.getText(_5d,true)+"\n"; }else{ if(_5b.parseError&&_5b.parseError.errorCode!=0){ _5c=Sarissa.PARSED_UNKNOWN_ERROR; } } } } return _5c; }; } Sarissa.getText=function(_5e,_5f){ var s=""; var _61=_5e.childNodes; for(var i=0;i<_61.length;i++){ var _63=_61[i]; var _64=_63.nodeType; if(_64==Node.TEXT_NODE||_64==Node.CDATA_SECTION_NODE){ s+=_63.data; }else{ if(_5f===true&&(_64==Node.ELEMENT_NODE||_64==Node.DOCUMENT_NODE||_64==Node.DOCUMENT_FRAGMENT_NODE)){ s+=Sarissa.getText(_63,true); } } } return s; }; if(!window.XMLSerializer&&Sarissa.getDomDocument&&Sarissa.getDomDocument("","foo",null).xml){ XMLSerializer=function(){ }; XMLSerializer.prototype.serializeToString=function(_65){ return _65.xml; }; } Sarissa.stripTags=function(s){ return s?s.replace(/<[^>]+>/g,""):s; }; Sarissa.clearChildNodes=function(_67){ while(_67.firstChild){ _67.removeChild(_67.firstChild); } }; Sarissa.copyChildNodes=function(_68,_69,_6a){ if(Sarissa._SARISSA_IS_SAFARI&&_69.nodeType==Node.DOCUMENT_NODE){ _69=_69.documentElement; } if((!_68)||(!_69)){ throw "Both source and destination nodes must be provided"; } if(!_6a){ Sarissa.clearChildNodes(_69); } var _6b=_69.nodeType==Node.DOCUMENT_NODE?_69:_69.ownerDocument; var _6c=_68.childNodes; var i; if(typeof (_6b.importNode)!="undefined"){ for(i=0;i<_6c.length;i++){ _69.appendChild(_6b.importNode(_6c[i],true)); } }else{ for(i=0;i<_6c.length;i++){ _69.appendChild(_6c[i].cloneNode(true)); } } }; Sarissa.moveChildNodes=function(_6e,_6f,_70){ if((!_6e)||(!_6f)){ throw "Both source and destination nodes must be provided"; } if(!_70){ Sarissa.clearChildNodes(_6f); } var _71=_6e.childNodes; if(_6e.ownerDocument==_6f.ownerDocument){ while(_6e.firstChild){ _6f.appendChild(_6e.firstChild); } }else{ var _72=_6f.nodeType==Node.DOCUMENT_NODE?_6f:_6f.ownerDocument; var i; if(typeof (_72.importNode)!="undefined"){ for(i=0;i<_71.length;i++){ _6f.appendChild(_72.importNode(_71[i],true)); } }else{ for(i=0;i<_71.length;i++){ _6f.appendChild(_71[i].cloneNode(true)); } } Sarissa.clearChildNodes(_6e); } }; Sarissa.xmlize=function(_74,_75,_76){ _76=_76?_76:""; var s=_76+"<"+_75+">"; var _78=false; if(!(_74 instanceof Object)||_74 instanceof Number||_74 instanceof String||_74 instanceof Boolean||_74 instanceof Date){ s+=Sarissa.escape(""+_74); _78=true; }else{ s+="\n"; var _79=_74 instanceof Array; for(var _7a in _74){ s+=Sarissa.xmlize(_74[_7a],(_79?"array-item key=\""+_7a+"\"":_7a),_76+" "); } s+=_76; } return (s+=(_75.indexOf(" ")!=-1?"</array-item>\n":"</"+_75+">\n")); }; Sarissa.escape=function(_7b){ return _7b.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"); }; Sarissa.unescape=function(_7c){ return _7c.replace(/&apos;/g,"'").replace(/&quot;/g,"\"").replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"); }; Sarissa.updateCursor=function(_7d,_7e){ if(_7d&&_7d.style&&_7d.style.cursor!=undefined){ _7d.style.cursor=_7e; } }; Sarissa.updateContentFromURI=function(_7f,_80,_81,_82,_83){ try{ Sarissa.updateCursor(_80,"wait"); var _84=new XMLHttpRequest(); _84.open("GET",_7f,true); _84.onreadystatechange=function(){ if(_84.readyState==4){ try{ var _85=_84.responseXML; if(_85&&Sarissa.getParseErrorText(_85)==Sarissa.PARSED_OK){ Sarissa.updateContentFromNode(_84.responseXML,_80,_81); if(_82){ _82(_7f,_80); } }else{ throw Sarissa.getParseErrorText(_85); } } catch(e){ if(_82){ _82(_7f,_80,e); }else{ throw e; } } } }; if(_83){ var _86="Sat, 1 Jan 2000 00:00:00 GMT"; _84.setRequestHeader("If-Modified-Since",_86); } _84.send(""); } catch(e){ Sarissa.updateCursor(_80,"auto"); if(_82){ _82(_7f,_80,e); }else{ throw e; } } }; Sarissa.updateContentFromNode=function(_87,_88,_89){ try{ Sarissa.updateCursor(_88,"wait"); Sarissa.clearChildNodes(_88); var _8a=_87.nodeType==Node.DOCUMENT_NODE?_87:_87.ownerDocument; if(_8a.parseError&&_8a.parseError.errorCode!=0){ var pre=document.createElement("pre"); pre.appendChild(document.createTextNode(Sarissa.getParseErrorText(_8a))); _88.appendChild(pre); }else{ if(_89){ _87=_89.transformToDocument(_87); } if(_88.tagName.toLowerCase()=="textarea"||_88.tagName.toLowerCase()=="input"){ _88.value=new XMLSerializer().serializeToString(_87); }else{ try{ _88.appendChild(_88.ownerDocument.importNode(_87,true)); } catch(e){ _88.innerHTML=new XMLSerializer().serializeToString(_87); } } } } catch(e){ throw e; } finally{ Sarissa.updateCursor(_88,"auto"); } }; Sarissa.formToQueryString=function(_8c){ var qs=""; for(var i=0;i<_8c.elements.length;i++){ var _8f=_8c.elements[i]; var _90=_8f.getAttribute("name")?_8f.getAttribute("name"):_8f.getAttribute("id"); if(_90&&((!_8f.disabled)||_8f.type=="hidden")){ switch(_8f.type){ case "hidden": case "text": case "textarea": case "password": qs+=_90+"="+encodeURIComponent(_8f.value)+"&"; break; case "select-one": qs+=_90+"="+encodeURIComponent(_8f.options[_8f.selectedIndex].value)+"&"; break; case "select-multiple": for(var j=0;j<_8f.length;j++){ var _92=_8f.options[j]; if(_92.selected===true){ qs+=_90+"[]"+"="+encodeURIComponent(_92.value)+"&"; } } break; case "checkbox": case "radio": if(_8f.checked){ qs+=_90+"="+encodeURIComponent(_8f.value)+"&"; } break; } } } return qs.substr(0,qs.length-1); }; Sarissa.updateContentFromForm=function(_93,_94,_95,_96){ try{ Sarissa.updateCursor(_94,"wait"); var _97=Sarissa.formToQueryString(_93)+"&"+Sarissa.REMOTE_CALL_FLAG+"=true"; var _98=new XMLHttpRequest(); var _99=_93.getAttribute("method")&&_93.getAttribute("method").toLowerCase()=="get"; if(_99){ _98.open("GET",_93.getAttribute("action")+"?"+_97,true); }else{ _98.open("POST",_93.getAttribute("action"),true); _98.setRequestHeader("Content-type","application/x-www-form-urlencoded"); _98.setRequestHeader("Content-length",_97.length); _98.setRequestHeader("Connection","close"); } _98.onreadystatechange=function(){ try{ if(_98.readyState==4){ var _9a=_98.responseXML; if(_9a&&Sarissa.getParseErrorText(_9a)==Sarissa.PARSED_OK){ Sarissa.updateContentFromNode(_98.responseXML,_94,_95); if(_96){ _96(_93,_94); } }else{ throw Sarissa.getParseErrorText(_9a); } } } catch(e){ if(_96){ _96(_93,_94,e); }else{ throw e; } } }; _98.send(_99?"":_97); } catch(e){ Sarissa.updateCursor(_94,"auto"); if(_96){ _96(_93,_94,e); }else{ throw e; } } return false; }; Sarissa.FUNCTION_NAME_REGEXP=new RegExp(""); Sarissa.getFunctionName=function(_9b,_9c){ var _9d; if(!_9d){ if(_9c){ _9d="SarissaAnonymous"+Sarissa._getUniqueSuffix(); window[_9d]=_9b; }else{ _9d=null; } } if(_9d){ window[_9d]=_9b; } return _9d; }; Sarissa.setRemoteJsonCallback=function(url,_9f,_a0){ if(!_a0){ _a0="callback"; } var _a1=Sarissa.getFunctionName(_9f,true); var id="sarissa_json_script_id_"+Sarissa._getUniqueSuffix(); var _a3=document.getElementsByTagName("head")[0]; var _a4=document.createElement("script"); _a4.type="text/javascript"; _a4.id=id; _a4.onload=function(){ }; if(url.indexOf("?")!=-1){ url+=("&"+_a0+"="+_a1); }else{ url+=("?"+_a0+"="+_a1); } _a4.src=url; _a3.appendChild(_a4); return id; }; if(Sarissa._SARISSA_HAS_DOM_FEATURE&&document.implementation.hasFeature("XPath","3.0")){ SarissaNodeList=function(i){ this.length=i; }; SarissaNodeList.prototype=[]; SarissaNodeList.prototype.constructor=Array; SarissaNodeList.prototype.item=function(i){ return (i<0||i>=this.length)?null:this[i]; }; SarissaNodeList.prototype.expr=""; if(window.XMLDocument&&(!XMLDocument.prototype.setProperty)){ XMLDocument.prototype.setProperty=function(x,y){ }; } Sarissa.setXpathNamespaces=function(_a9,_aa){ _a9._sarissa_useCustomResolver=true; var _ab=_aa.indexOf(" ")>-1?_aa.split(" "):[_aa]; _a9._sarissa_xpathNamespaces=[]; for(var i=0;i<_ab.length;i++){ var ns=_ab[i]; var _ae=ns.indexOf(":"); var _af=ns.indexOf("="); if(_ae>0&&_af>_ae+1){ var _b0=ns.substring(_ae+1,_af); var uri=ns.substring(_af+2,ns.length-1); _a9._sarissa_xpathNamespaces[_b0]=uri; }else{ throw "Bad format on namespace declaration(s) given"; } } }; XMLDocument.prototype._sarissa_useCustomResolver=false; XMLDocument.prototype._sarissa_xpathNamespaces=[]; XMLDocument.prototype.selectNodes=function(_b2,_b3,_b4){ var _b5=this; var _b6; if(this._sarissa_useCustomResolver){ _b6=function(_b7){ var s=_b5._sarissa_xpathNamespaces[_b7]; if(s){ return s; }else{ throw "No namespace URI found for prefix: '"+_b7+"'"; } }; }else{ _b6=this.createNSResolver(this.documentElement); } var _b9=null; if(!_b4){ var _ba=this.evaluate(_b2,(_b3?_b3:this),_b6,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); var _bb=new SarissaNodeList(_ba.snapshotLength); _bb.expr=_b2; for(var i=0;i<_bb.length;i++){ _bb[i]=_ba.snapshotItem(i); } _b9=_bb; }else{ _b9=this.evaluate(_b2,(_b3?_b3:this),_b6,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue; } return _b9; }; Element.prototype.selectNodes=function(_bd){ var doc=this.ownerDocument; if(doc.selectNodes){ return doc.selectNodes(_bd,this); }else{ throw "Method selectNodes is only supported by XML Elements"; } }; XMLDocument.prototype.selectSingleNode=function(_bf,_c0){ var ctx=_c0?_c0:null; return this.selectNodes(_bf,ctx,true); }; Element.prototype.selectSingleNode=function(_c2){ var doc=this.ownerDocument; if(doc.selectSingleNode){ return doc.selectSingleNode(_c2,this); }else{ throw "Method selectNodes is only supported by XML Elements"; } }; Sarissa.IS_ENABLED_SELECT_NODES=true; } Freja.QueryEngine=function(){ }; Freja.QueryEngine.prototype.getElementById=function(_c4,id){ var _c6=_c4.getElementsByTagName("*"); for(var i=0;i<_c6.length;i++){ if(_c6[i].getAttribute("id")==id){ return _c6[i]; } } }; Freja.QueryEngine.prototype.get=function(_c8,_c9){ var _ca=this._find(_c8,_c9); if(!_ca){ throw new Error("Can't evaluate expression "+_c9); } switch(_ca.nodeType){ case 1: if(_ca.firstChild&&(_ca.firstChild.nodeType==3||_ca.firstChild.nodeType==4)){ return _ca.firstChild.nodeValue; } break; case 2: return _ca.nodeValue; break; case 3: case 4: return _ca.nodeValue; break; } return null; }; Freja.QueryEngine.prototype.set=function(_cb,_cc,_cd){ var _ce=this._find(_cb,_cc); if(!_ce){ var _cf=_cc.substr(_cc.lastIndexOf("/")+1); if(_cf.charAt(0)=="@"){ var _d0=_cc.substring(0,_cc.lastIndexOf("/")); var _d1=this._find(_cb,_d0); if(_d1){ _d1.setAttribute(_cf.substr(1),_cd); return; } } throw new Error("Can't evaluate expression "+_cc); } switch(_ce.nodeType){ case 1: if(_ce.firstChild&&(_ce.firstChild.nodeType==3||_ce.firstChild.nodeType==4)){ _ce.firstChild.nodeValue=_cd; }else{ if(_cd!=""){ _ce.appendChild(_cb.createTextNode(_cd)); } } break; case 2: _ce.nodeValue=_cd; break; case 3: case 4: _ce.nodeValue=_cd; break; } return; }; Freja.QueryEngine.XPath=function(){ }; Freja.Class.extend(Freja.QueryEngine.XPath,Freja.QueryEngine); Freja.QueryEngine.XPath.prototype._find=function(_d2,_d3){ var _d4=_d2.selectSingleNode(_d3); return _d4; }; Freja.QueryEngine.SimplePath=function(){ }; Freja.Class.extend(Freja.QueryEngine.SimplePath,Freja.QueryEngine); Freja.QueryEngine.SimplePath.prototype._find=function(_d5,_d6){ if(!_d6.match(/^[\d\w\/@\[\]=_\-']*$/)){ throw new Error("SimplePath can't evaluate expression: "+_d6); } var _d7=_d6.split("/"); var _d8=_d5; var _d9=new RegExp("^@([\\d\\w]*)"); var _da=new RegExp("^([@\\d\\w]*)\\[([\\d]*)\\]$"); var _db=new RegExp("^([\\d\\w]+)\\[@([@\\d\\w]+)=['\"]{1}(.*)['\"]{1}\\]$"); var _dc=null; var _dd=0; for(var i=0;i<_d7.length;++i){ var _df=_d7[i]; var _e0=_db.exec(_df); if(_e0){ if(i>0&&_d7[i-1]==""){ var cn=_d8.getElementsByTagName(_e0[1]); }else{ var cn=_d8.childNodes; } for(var j=0,l=cn.length;j<l;j++){ if(cn[j].nodeType==1&&cn[j].tagName==_e0[1]&&cn[j].getAttribute(_e0[2])==_e0[3]){ _d8=cn[j]; break; } } if(j==l){ throw new Error("SimplePath can't evaluate expression "+_df); } }else{ _dd=_da.exec(_df); if(_dd){ _df=_dd[1]; _dd=_dd[2]-1; }else{ _dd=0; } if(_df!=""){ _dc=_d9.exec(_df); if(_dc){ _d8=_d8.getAttributeNode(_dc[1]); }else{ _d8=_d8.getElementsByTagName(_df).item(_dd); } } } } if(_d8&&_d8.firstChild&&_d8.firstChild.nodeType==3){ return _d8.firstChild; } if(_d8&&_d8.firstChild&&_d8.firstChild.nodeType==4){ return _d8.firstChild; } if(!_d8){ throw new Error("SimplePath can't evaluate expression "+_d6); } return _d8; }; Freja.Model=function(url,_e4){ this.url=url; this.ready=false; this.document=null; this._query=_e4; }; Freja.Model.prototype.getElementById=function(id){ if(this.document){ return this._query.getElementById(this.document,id); } return null; }; Freja.Model.prototype.get=function(_e6){ if(this.document){ return this._query.get(this.document,_e6); } return null; }; Freja.Model.prototype.set=function(_e7,_e8){ if(this.document){ return this._query.set(this.document,_e7,_e8); } return null; }; Freja.Model.prototype.updateFrom=function(_e9){ var _ea=_e9.getValues(); for(var i=0;i<_ea[0].length;++i){ if(_ea[0][i].lastIndexOf("/")!=-1){ try{ this.set(_ea[0][i],_ea[1][i]); } catch(x){ } } } }; Freja.Model.prototype.save=function(){ var url=this.url; var _ed=/^(file:\/\/.*\/)([^\/]*)$/.exec(window.location.href); if(_ed){ url=_ed[1]+url; } var d=Freja._aux.createDeferred(); var req=Freja.AssetManager.openXMLHttpRequest("POST",url); try{ Freja._aux.sendXMLHttpRequest(req,Freja._aux.serializeXML(this.document)).addCallbacks(Freja._aux.bind(d.callback,d),Freja._aux.bind(d.errback,d)); } catch(ex){ d.errback(ex); } return d; }; Freja.Model.prototype.remove=function(){ var url=this.url; var _f1=/^(file:\/\/.*\/)([^\/]*)$/.exec(window.location.href); if(_f1){ url=_f1[1]+url; } var req=Freja.AssetManager.openXMLHttpRequest("DELETE",url); return Freja._aux.sendXMLHttpRequest(req); }; Freja.Model.prototype.reload=function(url){ if(url){ for(var i=0;i<Freja.AssetManager.models.length;i++){ if(Freja.AssetManager.models[i].url==this.url){ Freja.AssetManager.models[i].url=url; } } this.url=url; } this.ready=false; var _f5=Freja._aux.bind(function(_f6){ this.document=_f6; this.ready=true; Freja._aux.signal(this,"onload"); },this); var d=Freja.AssetManager.loadAsset(this.url,true); d.addCallbacks(_f5,Freja.AssetManager.onerror); return d; }; Freja.Model.DataSource=function(_f8,_f9){ this.createURL=_f8; this.indexURL=_f9; }; Freja.Model.DataSource.prototype.select=function(){ return getModel(this.indexURL); }; Freja.Model.DataSource.prototype.create=function(_fa){ var url=this.createURL; var _fc=/^(file:\/\/.*\/)([^\/]*)$/.exec(window.location.href); if(_fc){ url=_fc[1]+url; } var req=Freja.AssetManager.openXMLHttpRequest("PUT",url); var _fe={}; for(var i=0,len=_fa[0].length;i<len;++i){ _fe[_fa[0][i]]=_fa[1][i]; } return Freja._aux.sendXMLHttpRequest(req,Freja._aux.xmlize(_fe,"record")); }; Freja.View=function(url,_101){ this.url=url; this.ready=false; this.document=null; this._renderer=_101; this._destination=null; this.behaviors=[]; this.placeholder=null; Freja._aux.connect(this,"onrendercomplete",Freja._aux.bind(this._connectBehavior,this)); }; Freja.View.prototype.render=function(_102,_103,_104){ if(typeof (_103)=="undefined"){ _103=this.placeholder; } if(typeof (_104)=="undefined"){ _104=this.xslParameters; } var _105=function(_106,view,_108,_109){ this.model=_106; this.view=view; this.deferred=_108; this.xslParameters=_109; }; _105.prototype.trigger=function(){ try{ if(!this.view.ready){ Freja._aux.connect(this.view,"onload",Freja._aux.bind(this.trigger,this)); return; } if(typeof (this.model)=="object"&&this.model instanceof Freja.Model&&!this.model.ready){ Freja._aux.connect(this.model,"onload",Freja._aux.bind(this.trigger,this)); return; } var _10a; if(typeof (this.model)=="undefined"){ _10a={document:Freja._aux.loadXML("<?xml version='1.0' ?><dummy/>")}; }else{ if(this.model instanceof Freja.Model){ _10a=this.model; }else{ _10a={document:Freja._aux.loadXML("<?xml version='1.0' ?>\n"+Freja._aux.xmlize(this.model,"item"))}; } } var _10b=this.view._renderer.transform(_10a,this.view,this.xslParameters); _10b.addCallback(Freja._aux.bind(function(html){ if(typeof html=="string"){ this._destination.innerHTML=html; }else{ this._destination.innerHTML=""; this._destination.appendChild(html); } },this.view)); _10b.addCallback(Freja._aux.bind(function(){ Freja._aux.signal(this,"onrendercomplete",this._destination); },this.view)); _10b.addCallback(Freja._aux.bind(function(){ this.deferred.callback(); },this)); _10b.addErrback(Freja._aux.bind(function(ex){ this.deferred.errback(ex); },this)); } catch(ex){ this.deferred.errback(ex); } }; var d=Freja._aux.createDeferred(); try{ if(typeof (_103)=="object"){ this._destination=_103; }else{ this._destination=document.getElementById(_103); } this._destination.innerHTML=Freja.AssetManager.THROBBER_HTML; var h=new _105(_102,this,d,_104); h.trigger(); } catch(ex){ d.errback(ex); } return d; }; Freja.View.prototype._connectBehavior=function(_110){ try{ var _111=function(node,_113,_114){ Freja._aux.connect(node,_113,Freja._aux.bind(function(e){ var _116=false; try{ _116=_114(this); } catch(ex){ throw new Error("An error ocurred in user handler.\n"+ex.message); } finally{ if(!_116){ e.stop(); } } },node)); }; var _117=function(node,_119){ for(var i=0,c=node.childNodes,l=c.length;i<l;++i){ var _11b=c[i]; if(_11b.nodeType==1){ if(_11b.className){ var _11c=_11b.className.split(" "); for(var j=0;j<_11c.length;j++){ var _11e=_119[_11c[j]]; if(_11e){ for(var _11f in _11e){ if(_11f=="init"){ _11e.init(_11b); }else{ _111(_11b,_11f,_11e[_11f]); } } } } } _117(_11b,_119); } } }; for(var ids in this.behaviors){ _117(_110,this.behaviors); break; } } catch(ex){ alert(ex.message); } }; Freja.View.prototype.getValues=function(){ return Freja._aux.formContents(this._destination); }; Freja.View.Renderer=function(){ }; Freja.View.Renderer.XSLTransformer=function(){ }; Freja.Class.extend(Freja.View.Renderer.XSLTransformer,Freja.View.Renderer); Freja.View.Renderer.XSLTransformer.prototype.transform=function(_121,view,_123){ var d=Freja._aux.createDeferred(); try{ var html=Freja._aux.transformXSL(_121.document,view.document,_123); if(!html){ d.errback(new Error("XSL Transformation error.")); }else{ d.callback(html); } } catch(ex){ d.errback(ex); } return d; }; Freja.View.Renderer.RemoteXSLTransformer=function(url){ this.url=url; }; Freja.Class.extend(Freja.View.Renderer.RemoteXSLTransformer,Freja.View.Renderer); Freja.View.Renderer.RemoteXSLTransformer.prototype.transform=function(_127,view,_129){ var d=Freja._aux.createDeferred(); var _12b=view.url; var _12c="xslFile="+encodeURIComponent(_12b)+"&xmlData="+encodeURIComponent(Freja._aux.serializeXML(_127.document)); var _12d=""; for(var _12e in _129){ _12d+=encodeURIComponent(_12e+","+_129[_12e]); } if(_12d.length>0){ _12c=_12c+"&xslParam="+_12d; } var req=Freja.AssetManager.openXMLHttpRequest("POST",Freja.AssetManager.XSLT_SERVICE_URL); req.onreadystatechange=function(){ if(req.readyState==4){ if(req.status==200){ d.callback(req.responseText); }else{ d.errback(req.responseText); } } }; req.send(_12c); return d; }; Freja.UndoHistory=function(){ this.cache=[]; this.maxLength=5; this._position=0; this._undoSteps=0; }; Freja.UndoHistory.prototype.add=function(_130){ var _131=this._position%this.maxLength; var _132=_130.document; this.cache[_131]={}; this.cache[_131].model=_130; this.cache[_131].document=Freja._aux.cloneXMLDocument(_132); if(!this.cache[_131].document){ throw new Error("Couldn't add to history."); }else{ this._position++; var _133=_131; while(this._undoSteps>0){ _133=(_133+1)%this.maxLength; this.cache[_133]={}; this._undoSteps--; } return _131; } }; Freja.UndoHistory.prototype.undo=function(_134){ if(this._undoSteps<this.cache.length){ this._undoSteps++; this._position--; if(this._position<0){ this._position=this.maxLength-1; } var _135=this.cache[this._position].model; if(this.cache[this._position].document){ _135.document=this.cache[this._position].document; }else{ throw new Error("The model's DOMDocument wasn't properly copied into the history"); } if(typeof (_134)!="undefined"&&_134>1){ this.undo(_134-1); } }else{ throw new Error("Nothing to undo"); } }; Freja.UndoHistory.prototype.redo=function(){ if(this._undoSteps>0){ this._undoSteps--; this._position=(this._position+1)%this.maxLength; var _136=this.cache[this._position].model; _136.document=this.cache[this._position].document; }else{ throw new Error("Nothing to redo"); } }; Freja.UndoHistory.prototype.removeLast=function(){ this._position--; if(this._position<0){ this._position=this.maxLength-1; } this.cache[this._position]={}; this._undoSteps=0; }; Freja.AssetManager={models:[],views:[],_username:null,_password:null}; Freja.AssetManager.HTTP_REQUEST_TYPE="async"; Freja.AssetManager.HTTP_METHOD_TUNNEL="Http-Method-Equivalent"; Freja.AssetManager.XSLT_SERVICE_URL="srvc-xslt.php"; Freja.AssetManager.THROBBER_HTML="<span style='color:white;background:firebrick'>Loading ...</span>"; Freja.AssetManager.createRenderer=function(){ if(Freja._aux.hasSupportForXSLT()){ return new Freja.View.Renderer.XSLTransformer(); }else{ return new Freja.View.Renderer.RemoteXSLTransformer(this.XSLT_SERVICE_URL); } }; Freja.AssetManager.clearCache=function(){ this.models=[]; this.views=[]; }; Freja.AssetManager.getModel=function(url){ for(var i=0;i<this.models.length;i++){ if(this.models[i].url==url){ return this.models[i]; } } var m=new Freja.Model(url,Freja._aux.createQueryEngine()); var _13a=Freja._aux.bind(function(_13b){ this.document=_13b; this.ready=true; Freja._aux.signal(this,"onload"); },m); this.loadAsset(url,true).addCallbacks(_13a,Freja.AssetManager.onerror); this.models.push(m); return m; }; Freja.AssetManager.getView=function(url){ for(var i=0;i<this.views.length;i++){ if(this.views[i].url==url){ return this.views[i]; } } var v=new Freja.View(url,this.createRenderer()); var _13f=Freja._aux.bind(function(_140){ this.document=_140; this.ready=true; Freja._aux.signal(this,"onload"); },v); this.loadAsset(url,false).addCallbacks(_13f,Freja.AssetManager.onerror); this.views.push(v); return v; }; Freja.AssetManager.openXMLHttpRequest=function(_141,url){ var _143=null; if(Freja.AssetManager.HTTP_METHOD_TUNNEL&&_141!="GET"&&_141!="POST"){ _143=_141; _141="POST"; } var req=Freja._aux.openXMLHttpRequest(_141,url,Freja.AssetManager.HTTP_REQUEST_TYPE=="async",Freja.AssetManager._username,Freja.AssetManager._password); if(_143){ req.setRequestHeader(Freja.AssetManager.HTTP_METHOD_TUNNEL,_143); } return req; }; Freja.AssetManager.setCredentials=function(_145,_146){ this._username=_145; this._password=_146; }; Freja.AssetManager.loadAsset=function(url,_148){ var _149=/^(file:\/\/.*\/)([^\/]*)$/.exec(window.location.href); if(_149){ url=_149[1]+url; } var d=Freja._aux.createDeferred(); var _14b=function(_14c){ try{ if(_14c.responseText==""){ throw new Error("Empty response."); } if(_14c.responseXML.xml==""){ var _14d=Freja._aux.loadXML(_14c.responseText); }else{ var _14d=_14c.responseXML; } } catch(ex){ d.errback(ex); } if(Freja.AssetManager.HTTP_REQUEST_TYPE=="async"&&window.document.all){ setTimeout(function(){ d.callback(_14d); },1); }else{ d.callback(_14d); } }; try{ if(_148&&Freja.AssetManager.HTTP_METHOD_TUNNEL){ var req=Freja._aux.openXMLHttpRequest("POST",url,Freja.AssetManager.HTTP_REQUEST_TYPE=="async",Freja.AssetManager._username,Freja.AssetManager._password); req.setRequestHeader(Freja.AssetManager.HTTP_METHOD_TUNNEL,"GET"); req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); }else{ var req=Freja._aux.openXMLHttpRequest("GET",url,Freja.AssetManager.HTTP_REQUEST_TYPE=="async",Freja.AssetManager._username,Freja.AssetManager._password); } var comm=Freja._aux.sendXMLHttpRequest(req); if(Freja.AssetManager.HTTP_REQUEST_TYPE=="async"){ comm.addCallbacks(_14b,function(req){ d.errback(new Error("Request failed:"+req.status)); }); }else{ if(req.status==0||req.status==200||req.status==201||req.status==304){ _14b(req); }else{ d.errback(new Error("Request failed:"+req.status)); } } } catch(ex){ d.errback(ex); } return d; }; Freja.AssetManager.onerror=function(ex){ alert("Freja.AssetManager.onerror\n"+ex.message); }; window.getModel=Freja._aux.bind("getModel",Freja.AssetManager); window.getView=Freja._aux.bind("getView",Freja.AssetManager);
var beatles = ["John", "Paul", "George", "Ringo"]; //This is a for loop for(var i = beatles.length -1; i>=0; i--) { console.log("Hello, my name is " + beatles[i]) }
var EventManager = (function (_super) { __extends(EventManager, _super); function EventManager() { _super.apply(this, arguments); } var d = __define,c=EventManager;p=c.prototype; d(EventManager, "instance" ,function () { if (!EventManager._instance) { EventManager._instance = new EventManager(); } return EventManager._instance; } ); p.addEvent = function (type, callback, targetObj) { this.addEventListener(type, callback, targetObj); }; p.removeEvent = function (type, callback, targetObj) { this.removeEventListener(type, callback, targetObj); }; p.dispatch = function (type, data) { if (data === void 0) { data = null; } this.dispatchEventWith(type, false, data); }; return EventManager; })(egret.EventDispatcher); egret.registerClass(EventManager,"EventManager");
// Day 2 Excercise 2 var words = [ 'Laptop','bus' , 'Parking', 13 ,'453']; var lengths = words.map(function(word){ console.log(word.length); })
import {BOX_TRIANGLE_INDICES} from "src/geo/Box.js"; import {seq} from "src/base/Seq.js"; import {Triangle} from "src/geo/Triangle.js"; class Ray { /** * @param {!Point} start * @param {!Vector} direction */ constructor(start, direction) { this.start = start; this.direction = direction.unit(); } /** * @param {!Plane} plane * @param {!number} epsilon * @returns {undefined|!Point} */ intersectPlane(plane, epsilon) { let scalarDistance = plane.center.minus(this.start).dot(plane.normal); let scalarDirection = this.direction.dot(plane.normal); if (Math.abs(scalarDirection) < epsilon) { return undefined; } let t = scalarDistance / scalarDirection; if (t < -epsilon) { return undefined; } return this.start.plus(this.direction.scaledBy(t)); } /** * @param {!Triangle} triangle * @param {!number} epsilon * @returns {undefined|!Point} */ intersectTriangle(triangle, epsilon) { let pt = this.intersectPlane(triangle.plane(), epsilon); if (pt === undefined || !triangle.containsPoint(pt, epsilon)) { return undefined; } return pt; } /** * @param {!Array.<!Point>} pts * @returns {!Point} */ firstPoint(pts) { return seq(pts).minBy(pt => pt.minus(this.start).dot(this.direction)); } /** * @param {!Box} box * @param {!number} epsilon * @returns {undefined|!Point} */ intersectBox(box, epsilon) { let corners = box.renderPoints(); let pts = []; for (let i = 0; i < BOX_TRIANGLE_INDICES.length; i += 3) { let t = new Triangle( corners[BOX_TRIANGLE_INDICES[i]], corners[BOX_TRIANGLE_INDICES[i + 1]], corners[BOX_TRIANGLE_INDICES[i + 2]]); let pt = this.intersectTriangle(t, epsilon); if (pt !== undefined) { pts.push(pt); } } if (pts.length === 0) { return undefined; } return this.firstPoint(pts); } /** * @param {*|!Plane} other * @returns {!boolean} */ isEqualTo(other) { return other instanceof Ray && this.start.isEqualTo(other.start) && this.direction.isEqualTo(other.direction); } /** * @param {*|!Plane} other * @param {!number} epsilon * @returns {!boolean} */ isApproximatelyEqualTo(other, epsilon) { return other instanceof Ray && this.start.isApproximatelyEqualTo(other.start, epsilon) && this.direction.isApproximatelyEqualTo(other.direction, epsilon); } /** * @returns {!string} */ toString() { return `${this.start} + t*${this.direction}`; } } export {Ray}
const mongoose = require("mongoose"); const { isEmail } = require("validator"); const bcrypt = require("bcrypt"); const { NotExtended } = require("http-errors"); const userSchema = new mongoose.Schema({ name: { type: String, required: [true, "please enter a user name"], minlength: 3, }, email: { type: String, required: [true, "please enter an email"], minlength: 6, unique: true, lowercase: true, validate: [isEmail, `please enter a valid email`], }, password: { type: String, required: [true, "please enter a password"], minlength: [6, "minimum password length 6 character"], }, date: { type: Date, default: Date.now, }, admin: { type: Boolean, default: false, }, firstName: String, secondName: String, address: String, city: String, phone: String, }); userSchema.pre("save", async function () { const salt = await bcrypt.genSalt(); this.password = await bcrypt.hash(this.password, salt); }); //static method to login user userSchema.statics.login = async function (email, password) { try { const user = await this.findOne({ email }); if (user) { const auth = await bcrypt.compare(password, user.password); if (auth) { return user; } throw Error("incorrect password"); } throw Error("incorrect email"); } catch (err) { console.log(err); } }; const User = mongoose.model("user", userSchema); module.exports = User;
export default { dashboard: { text: 'Dashboard', icon: 'calculator', path: '/', name: 'dashboard' }, outlets: { text: 'Outlet', icon: 'store', path: '/outlets', name: 'outlets' }, products: { text: 'Products', icon: 'box', path: '/products', name: 'products' }, variants: { text: 'Manage variants', icon: 'box', path: '/products/variants', name: 'products.variants' }, categories: { text: 'Manage categories', icon: 'box', path: '/products/categories', name: 'products.categories' }, devices: { text: 'Devices', icon: 'tablet-alt', path: '/devices', name: 'devices' }, statistics_and_reports: { text: 'Statistics & Reports', icon: 'chart-line', path: '/statistics-and-reports', name: 'statistics-and-reports' }, accounts: { text: 'Accounts', icon: 'user-circle', path: '/accounts', name: 'accounts' }, settings: { text: 'Settings', icon: 'wrench', path: '/settings', name: 'settings' } }
import React, { Component } from 'react' import { Link } from 'react-router-dom' import { withRouter } from 'react-router' class Header extends Component { render() { return ( <div className="flex pa1 justify-between nowrap orange"> <div className="flex flex-fixed black"> <div className="fw7 mr1">Lista de Clase</div> <Link to="/" className="ml1 no-underline black"> Lista </Link> <div className="ml1">|</div> <Link to="/crear" className="ml1 no-underline black"> Agregar </Link> <div className="ml1">|</div> <Link to="/eliminar" className="ml1 no-underline black"> Eliminar </Link> <div className="ml1">|</div> <Link to="/modificar" className="ml1 no-underline black"> Modificar </Link> </div> </div> ) } } export default withRouter(Header)
import React from 'react'; // import './serversearchinput.css' import imgJiahao from '../../../../assets/images/serveradd.png' import SearchBox from '../../../../common/searchbox/SearchBox' // import {SearchBox} from './style.js' const ServerSearchInput=(props)=> { const {handlenOnclick,SearchBoxhandleOnclick}=props; return ( <> <SearchBox icon={()=>{ return( <img style={ { marginLeft :".3889rem" , width:".7315rem", height: ".7315rem"}} src={imgJiahao} onClick={()=>{handlenOnclick()}}/> ) }} SearchBoxhandleOnclick={SearchBoxhandleOnclick}/> </> ); } export default ServerSearchInput;
var app = angular.module('remindServer',[]); app.factory('remindSer',function ($http) { return { remindList:remindList, remindId:remindId, remindCount:remindCount, remindDelete:remindDelete, remindAdd:remindAdd, remindEdit:remindEdit, getProjectTask:getProjectTask, getNameTask:getNameTask, getTableTask:getTableTask, remindPermission:remindPermission }; //菜单权限 function remindPermission(data) { return $http.get('/websitePermission/permission/'+data); } function remindList(data) { return $http.get('/remindList/list',{ params: data }) } //添加 function remindAdd(data){ return $http.post('/remindAdd/add',data) } //编辑 function remindEdit(data){ return $http.post('/remindEdit/edit',data) } //id查询 function remindId(data){ return $http.get('/remindId/id',{ params:data }) } //分页总条数 function remindCount(data){ return $http.get('/remindCount/count',{params:data}) } //删除 function remindDelete(data){ return $http.get('/remindDelete/delete',{ params: data }) } //获取所有项目名称 function getProjectTask(data){ return $http.get('/getProjectTask/project',{ params: data }) } //根据项目表获取任务名 function getNameTask(data){ return $http.get('/getNameTask/name',{ params: data }) } //根据项目获取项目表 function getTableTask(data){ return $http.get('/getTableTask/table',{ params: data }) } });
'use strict'; // модуль, который экспортирует в глобальную область видимости функции для взаимодействия с удаленным севером через XHR (function () { var GET_URL = 'https://js.dump.academy/candyshop/data'; var SUBMIT_URL = 'https://js.dump.academy/candyshop'; var STATUS_SUCCESS = 200; var STATUS_NOT_FOUND = 404; var STATUS_SERVER_ERROR = 500; var TIMEOUT_TIME = 10000; var setupRequest = function (xhr, successCallback, errorCallback) { xhr.responseType = 'json'; xhr.addEventListener('load', function () { var error; switch (xhr.status) { case STATUS_SUCCESS: successCallback(xhr.response); break; case STATUS_NOT_FOUND: error = 'Ничего не найдено'; break; case STATUS_SERVER_ERROR: error = 'Сервер не отвечает'; break; default: error = 'Cтатус ответа: : ' + xhr.status + ' ' + xhr.statusText; } if (error) { xhr(error); } }); xhr.addEventListener('error', function () { errorCallback('Произошла ошибка соединения'); }); xhr.addEventListener('timeout', function () { errorCallback('Запрос не успел выполниться за ' + TIMEOUT_TIME + 'мс'); }); xhr.timeout = TIMEOUT_TIME; }; window.backend = { load: function (onSuccess, onError) { var xhr = new XMLHttpRequest(); setupRequest(xhr, onSuccess, onError); xhr.open('GET', GET_URL); xhr.send(); }, upload: function (data, onSuccess, onError) { var xhr = new XMLHttpRequest(); setupRequest(xhr, onSuccess, onError); xhr.open('POST', SUBMIT_URL); xhr.send(data); }, showErrorPopup: function () { var errorPopupElement = document.querySelector('#modal-error'); window.utils.showPopup(errorPopupElement); }, showSuccessPopup: function () { var succesPopupElement = document.querySelector('#modal-success'); window.utils.showPopup(succesPopupElement); } }; })();
// Initialize Cloud Firestore through Firebase var firebaseConfig = { apiKey: "AIzaSyCVNlvi9zyb8HD30nXyAimeU4VDn-6k3Pk", authDomain: "legendariogaming-58719.firebaseapp.com", projectId: "legendariogaming-58719", storageBucket: "legendariogaming-58719.appspot.com", messagingSenderId: "893806069957", appId: "1:893806069957:web:c3aade3d6714b3b53988ac" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); console.log("Cargado correctamente") var db = firebase.firestore() console.log(db) var tabla = document.getElementById("tabla") db.collection("tienda").get().then((querySnapshot)=>{ tabla.innerHTML=""; querySnapshot.forEach((doc)=>{ tabla.innerHTML+=` <tr> <th scope="row">${doc.id}</th> <th scope="row">${doc.data().Consola}</th> <th scope="row">${doc.data().Descripcion}</th> <th scope="row">${doc.data().Precio}</th> <th scope="row">${doc.data().Videojuego}</th> </tr> ` }) })
import React from "react"; import Pomodoro from "./Pomodoro"; import "./css/Home.css"; import stats_icon from "./images/stats_icon.svg"; import { useHistory } from "react-router-dom"; export default class Home extends React.Component { render() { return ( <div> <div id="top-bar"> <TopBar /> </div> <div id="pomodoro"> <Pomodoro /> </div> </div> ); } } function TopBar(props) { let history = useHistory(); return ( <div> <img className="icon" id="history-icon" onClick={() => history.push("/stats")} src={stats_icon} alt="icon for stats" /> </div> ); }
import head from './config/head' import scrollBehavior from './router.scrollBehavior.js' require('dotenv').config() export default { mode: 'spa', /* ** Headers of the page */ head, generate: { fallback: true }, loading: { color: '#fff' }, css: ['@/assets/scss/main.scss'], plugins: [ '~plugins/vue-vee-validate.js', '~plugins/vue2-google-maps.js', '~/plugins/vue-click-outside.js', '~/plugins/vue-youtube.js', { src: '~/plugins/vue-infinite-scroll', ssr: false } ], buildModules: ['@nuxtjs/eslint-module', '@nuxtjs/tailwindcss'], modules: [ '@nuxtjs/axios', '@nuxtjs/pwa', '@nuxtjs/dotenv', '@nuxtjs/auth', '@nuxtjs/apollo' ], router: { // middleware: ['auth'], scrollBehavior }, axios: { baseURL: process.env.API_URL, headers: { common: { 'X-Requested-With': 'XMLHttpRequest' } } }, apollo: { clientConfigs: { default: { httpEndpoint: `${process.env.API_URL}graphql` } } // Doesn't work. Here: https://github.com/apollographql/apollo-client/issues/2555 // defaultOptions: { // $query: { fetchPolicy: 'no-cache', errorPolicy: 'all' }, // $mutate: { errorPolicy: 'all' } // } }, auth: { strategies: { local: { endpoints: { login: { url: '/api/c/login', method: 'post', propertyName: 'access_token' }, logout: { url: '/api/c/logout', method: 'post' }, user: { url: '/api/c/me', method: 'get', propertyName: 'data' } } } }, redirect: { logout: '/login' } }, build: { extend(config, ctx) {}, vendor: ['vue2-google-maps'] } }
import React, { PureComponent } from 'react' class NoSites extends PureComponent { render() { return ( <div className="s12 m12"> <div className="card" style={{ backgroundColor: this.props.color }}> <div className={ 'card-content ' + this.props.textColor }> <span className="card-title center" style={{ display: 'block' }}>Welcome to reactStartPage<sup>4</sup></span> <p className="center">A project by <a href="https://twitter.com/mattarnster">@mattarnster</a> and these <a href="https://github.com/mattarnster/reactStartPage3/contributors" target="_blank" rel="noopener noreferrer">contributors</a> on GitHub</p> <br /> <p className="center">This is your own personal start page. <br /> All of your data is stored locally within your web-browser.</p> <br /> <p className="center">Click 'Manage Sites' in the top-left to get started!</p> </div> </div> </div> ) } } export default NoSites
/*################################################# For: SSW 322 By: Bruno, Hayden, Madeline, Miriam, and Scott #################################################*/ const https = require('https'); const parseString = require('xml2js').parseString; const Tokenizer = require('sentence-tokenizer'); const key = require('../../private').GOODREADS_KEY; var getRequest = async function (url, extension, xml, callback) { var type = 'json' if (xml) { type = 'xml' }; var options = { hostname: url, port: 443, path: extension, method: 'GET', headers: { 'Content-Type': 'application/' + type } }; const port = options.port == 443 ? https : http; let output = ''; const req = port.request(options, (res) => { res.setEncoding('utf8'); res.on('data', (chunk) => { output += chunk; }); res.on('end', () => { if(xml) { parseString(output, (err, data) => { book = data.GoodreadsResponse; callback(book); }) } else { callback(output); } }); }); req.on('error', error => { res.send('error: ' + error.message); }); req.end(); } var cleanText = function (rawText) { // Could be done so much betetr but why question it if it works lol var noB = rawText.split('<b>').join(''); var noOtherB = noB.split('</b>').join(''); var cleanText = noOtherB.split('<br />').join(' '); var cleanerText = cleanText.split('<i>').join(' '); var cleanestText = cleanerText.split('</i>').join(' '); var cleanerText1 = cleanestText.split('<div>').join(' '); var cleanestText1 = cleanerText1.split('</div>').join(' '); var cleanerText2 = cleanestText1.split('<p>').join(' '); var cleanestText2 = cleanerText2.split('</p>').join(' '); var cleanerText3 = cleanestText2.split('<blockquote>').join(' '); var cleanestText3 = cleanerText3.split('</blockquote>').join(' '); var tokenizer = new Tokenizer('Description'); tokenizer.setEntry(cleanestText2); var description = tokenizer.getSentences()[0] + ' ' + tokenizer.getSentences()[1]; return [cleanestText2, description]; } module.exports = async function (bookID, callback) { getRequest('www.goodreads.com', '/book/show/' + bookID + '?key=' + key, true, function(book){ book = book.book[0]; var text = cleanText(book.description[0]); var image = book.image_url[0].split('._SY160_').join(''); var imageClean = image.split('._SX98_').join(''); if (imageClean.includes('nophoto')) { imageClean = 'https://i.pinimg.com/474x/49/60/7c/49607c19eaf6e456ac6f06ad4688f337.jpg' } bookData = { 'bookID' : book.id[0], 'title' : book.title[0], 'isbn' : book.isbn[0], 'isbn13' : book.isbn13[0], 'description' : text[0], 'shortDescription' : text[1], 'author' : book.authors[0].author[0].name[0], 'pages' : book.num_pages[0], 'imgURL' : imageClean, 'rating' : book.average_rating[0], 'numberOfRatings' : Number(book.ratings_count[0]), 'purchaseURL' : 'https://www.amazon.com/s?k=' +book.isbn[0] + '&ref=haydendaly-20' }; callback(bookData); }); }
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ from : {type :Schema.Types.ObjectId, ref : 'User'}, to : {type :Schema.Types.ObjectId, ref : 'User'}, pair : {from : Number, to : Number}, name : String, count : {type : Number, default : 1}, score : {type : Number, default : 0}, createTime : {type : Date, default : Date.now}, duration : {type : Number,default : 0} }); schema.virtual('expire').get(function() { if (this.duration===0) return false; return this.createTime.getTime() + this.duration < Date.now(); }); schema.virtual('total_score').get(function(){ return this.count * this.createTime; }); module.exports = mongoose.model('gift', schema);
const { sumTokensAndLPsSharedOwners } = require("../helper/unwrapLPs"); const sdk = require('@defillama/sdk'); const erc20 = require("../helper/abis/erc20.json"); const { transformFantomAddress } = require("../helper/portedTokens"); const { unwrapUniswapLPs } = require("../helper/unwrapLPs") const { getBlock } = require('../helper/getBlock'); const hectorStakingv1 = "0x9ae7972BA46933B3B20aaE7Acbf6C311847aCA40" const hectorStakingv2 = "0xD12930C8deeDafD788F437879cbA1Ad1E3908Cc5" const hec = "0x5C4FDfc5233f935f20D2aDbA572F770c2E377Ab0" const hecDaiSLP = "0xbc0eecdA2d8141e3a26D2535C57cadcb1095bca9" const treasury = "0xCB54EA94191B280C296E6ff0E37c7e76Ad42dC6A" const dai = "0x8d11ec38a3eb5e956b052f67da8bdc9bef8abf3e" const ftm = "0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83" const hecUsdcLP = "0xd661952749f05acc40503404938a91af9ac1473b" const usdc = "0x04068da6c83afcfa0e13ba15a6696662335d5b75" const HectorStakings = [ // V1 hectorStakingv1, // V2 hectorStakingv2, ]; async function tvl(timestamp, block, chainBlocks) { const balances = {}; const transformAddress = await transformFantomAddress(); await sumTokensAndLPsSharedOwners( balances, [ [dai, false], [usdc, false], [ftm, false], [hecUsdcLP, true], [hecDaiSLP, true] ], [treasury], chainBlocks.fantom, 'fantom', transformAddress ); return balances; } /*** Staking of native token (OHM) TVL Portion ***/ const staking = async (timestamp, ethBlock, chainBlocks) => { const chain = "fantom"; let stakingBalance, totalBalance = 0; const block = await getBlock(timestamp, chain, chainBlocks) for (const stakings of HectorStakings) { stakingBalance = await sdk.api.abi.call({ abi: erc20.balanceOf, target: hec, params: stakings, chain: chain, block: block, }); totalBalance += Number(stakingBalance.output); } const address = `${chain}:${hec}` return { [address]: totalBalance } }; module.exports = { misrepresentedTokens: true, fantom: { tvl, staking }, methodology: "TVL consists of tokens that have been bonded on the protocol and staking consist of the native tokens that have been deposited to the staking contract", };
const fs = require('fs'); const path = require('path'); const promisify = require('util').promisify; const stat = promisify(fs.stat); const readdir = promisify(fs.readdir); const artTemplate = require('art-template'); const mime = require('./mime'); const compress = require('./compress'); const range = require('./range'); const toCache = require('./cache');//判断是否去缓存读取 const tplPath = path.join(__dirname, '../template/dir.html'); module.exports = async function (req, res, filePath,conf) { try { const stats = await stat(filePath); if (stats.isFile()) { let ext = mime(filePath); res.setHeader('content-type', ext); if(toCache(stats,req,res)){ res.statusCode=304; res.end(); return; } const {code,start,end}=range(stats.size,req,res); var rs; //206表示获取部分内容 200返回所有内容 if(code==200){ res.statusCode = 200; rs = fs.createReadStream(filePath); }else{ res.statusCode = 206; rs = fs.createReadStream(filePath,{start,end}); } if(filePath.match(conf.compress)){ rs = compress(rs, req, res); } rs.pipe(res); } else if (stats.isDirectory()) { const files = await readdir(filePath); const dir = path.relative(conf.root, filePath); const title = path.basename(filePath); var html = artTemplate(tplPath, { files, dir:dir?`/${dir}`:'', title }); res.writeHead(200, { 'content-type': 'text/html' }); res.end(html); } } catch (err) { console.log(err); res.writeHead(404); res.end(`${filePath} is not a directory or file`); } }
import React from 'react'; import H2Element from '../styled/H2Element'; import H2Element from '../styled/H2Element'; const Education = () => ( <div className="Education"> <H2Element name="Mis Estudios /> <div className="Education_container"> <div className="Education__item"> <h3>PCJIC</h3> <p>Desarrollador WEB</p> </div> </div> </div> ); export default Education;
import React from 'react'; //Allows React to be used in this component import ReactDOM from 'react-dom'; //Allows the React library to be used in this component import logo from '../../src/logo.svg'; //Allows logo class to be used in this component import '../App.css'; //Allows style sheet to be used for this component //React.component tells React what needs to be rendered, in this case the App class //App class displays React logo on my app class App extends React.Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> </div> </div> ); } } export default App; //Export allows the class to be used elsewhere in the app
import React from 'react'; import Content from "./ContentPage"; import ContactUs from "./contact"; import About from "./About"; import Tech from "./Tech"; const Portfolio = () => { return ( <div> <About/> <Tech/> <Content/> <ContactUs/> </div> ); }; export default Portfolio;
import React, { Component } from 'react' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' export default class registerpage extends Component { render() { return ( <div class="wrapper-signup"> <div class="login"> <div> <form action="#" class="form-login"> <div class="field-input"> <input type="text" placeholder="Fullname" class="sign-up" /> </div> <div class="field-input"> <input type="text" placeholder="Email" class="sign-up" required /> </div> <div class="field-input"> <input type="password" placeholder="Password" class="sign-up" /> </div> <div class="btn-register"> <button type="submit" class="btn-reg" name="button">Register</button> </div> </form> </div> <div> <p class="form-text">Already registred! <Link to="/">Login me</Link>.</p> </div> </div> </div> ) } }
var app = app || {}; app.ExampleView = Backbone.View.extend( { template: _.template($('#map-example-template').html()), initialize: function() { //render blank template this.$el.html(this.template); this.$map = this.$('.map-div'); this.$controls = this.$('.control-div'); this.render(); }, render: function() { //create new map pane (minor kludge to update map size after rendering //which prevents weird leaflet behaviour var mapView = new app.MapView({collection:this.collection}); this.$map.html(mapView.render()); mapView.map.invalidateSize(); //create a new map control view var controlView = new app.ControlSectionView({collection:this.collection}); this.$controls.html(controlView.render()); return this; } });
import React from "react"; import { connect } from "react-redux"; import { add_client_order } from "../../actions/client-actions"; import Form from "../../components/Form/form"; const inputsList = { brand: "", model: "", imei: "", description: "", wishes: "", repairStart: "" }; // active const inputs = [ { label: "Бренд", variant: "outlined", type: "text", name: "brand" }, { label: "Модель", variant: "outlined", type: "text", name: "model" }, { label: "imei", variant: "outlined", type: "number", name: "imei" }, { label: "Описание", variant: "outlined", type: "text", name: "description" }, { label: "Особые пожелания", variant: "outlined", type: "text", name: "wishes" }, { label: "Начало ремонта", variant: "outlined", type: "text", name: "repairStart" } ]; const OrderForm = ({ add_client_order, match, history }) => { const onSubmit = (e, formData) => { e.preventDefault(); add_client_order(match.params.id, formData, history); }; return ( <Form formHeader="Введите данные для добавления" submit={onSubmit} submitTitle="Добавить" inputsData={inputsList} inputs={inputs} /> ); }; const mapDispatchToProps = dispatch => ({ add_client_order: (id, formData, history) => dispatch(add_client_order(id, formData, history)) }); export default connect(() => {}, mapDispatchToProps)(OrderForm);
import React from 'react'; import { ToastContainer, toast } from 'react-toastify'; /** * Logout user * */ class Logout extends React.Component{ componentDidMount(){ localStorage.removeItem('Token') localStorage.removeItem('user_id') localStorage.removeItem('username') // redirect back to login this.props.history.push('/'); toast.success("Logged out Successfully"); } render(){ return( <div> <ToastContainer autoClose={2000}hideProgressBar={true} /> </div> ); } } export default Logout;
import React, { Component } from 'react'; import { Text, View, StyleSheet, Linking, ActivityIndicator } from 'react-native'; import { FlatList } from 'react-native-gesture-handler'; import RenderNewsItem from '../Components/NewsDetails'; class News extends Component { intervalID; state = { arr: [], isLoading: true }; componentDidMount() { this.getNewsFrom(); } getNewsFrom = async () => { let url = 'https://min-api.cryptocompare.com/data/v2/news/?lang=EN'; await fetch(url) .then((response) => response.json()) .then((data) => { this.setState({ arr: data.Data }); this.intervalID = setTimeout(this.getNewsFrom.bind(this), 10000); }); this.setState({ isLoading: false }); }; componentWillMount() { clearTimeout(this.intervalID); } static navigationOptions = { title: 'News' }; render() { this.state.arr.map((value) => { console.log(value.url); }); if (this.state.isLoading) { return ( <View style={[styles.container, styles.horizontal]}> <ActivityIndicator size="large" color="#0000ff" /> </View> ); } return ( <FlatList keyExtractor={(item, index) => item.id} data={this.state.arr} renderItem={({ item }) => ( <RenderNewsItem title={item.title} image={item.imageurl} name={item.source_info.name} category={item.categories} published_on={item.published_on} onSelect={() => { Linking.openURL(item.url); }} /> )} numColumns={2} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center' } }); export default News;
import BookLayout from './BookLayout'; import LinkLayout from './LinkLayout'; export { BookLayout, LinkLayout }
import Popup from './Popup.js' export default class PopupWithImage extends Popup{ constructor(formPopup, formPhoto, formCaption){ super(formPopup) this._formPhoto = this._popup.querySelector(formPhoto); this._formCaption = this._popup.querySelector(formCaption); } open(name, link){ this._formCaption.textContent = name; this._formPhoto.src = link; this._formPhoto.alt = name; super.open(); } }
import React from 'react'; import { BrowserRouter as Router } from "react-router-dom"; import './App.css'; import { Provider } from 'react-redux'; import { applyMiddleware, createStore } from 'redux'; import promise from 'redux-promise' import multi from 'redux-multi'; import thunk from 'redux-thunk'; import Menu from '../template/menu'; import Routes from './routes'; import rootReducers from './reducers'; const devTools = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(); /** * nesse caso estamos a usar o applyMiddleware e o promise, porq estamos a fazer uma chama assincrona e o nosso action retorna * um chamada ou uma promisse n resolvida */ /** * multi - esse midleware permite disparar várias acoes dentro de uma ínica func de action. */ const store = applyMiddleware(thunk, multi, promise)(createStore)(rootReducers, devTools); function App() { return ( <Provider store={store}> <div className="App container"> <Router> <Menu /> <Routes /> </Router> </div> </Provider> ); } export default App;
function rollover(){ $("img[src*='_on']").addClass("current"); $("img,input[type='image']").hover(function(){ if ($(this).attr("src")){ $(this).attr("src",$(this).attr("src").replace("_off.", "_on.")); } },function(){ if ($(this).attr("src") && !$(this).hasClass("current") ){ $(this).attr("src",$(this).attr("src").replace("_on.", "_off.")); } }); }
// /** // * Created by elinaguo on 16/1/31. // */ // 'use strict'; // var agent = require('superagent').agent(); // var config = require('../../config/config'); // exports.repayThePaymentRecord = function(userId, paymentId, deviceId, callback){ // console.log('repay payment record=================='); // console.error('userId', userId); // console.error('paymentId', paymentId); // console.error('deviceId', deviceId); // var url = config.business.serverAddress + config.business.repay; // agent.post(url) // .set('Content-Type', 'application/x-www-form-urlencoded') // .send({ // user_id: userId, // payment_id: paymentId, // device_registration_id: deviceId // }) // .end(function (err, res) { // return callback(err, res.body); // }); // };
({ baseUrl:"../../libs/rdk/", name: "rdk", out: "main.min.js", mainConfigFile : "../../libs/rdk/mainconfig.js", findNestedDependencies : true, separateCSS: true, paths: { base: 'd:\\Code\\rdk\\rdk\\app\\example\\web\\', helper: 'd:\\Code\\rdk\\rdk\\app\\modules\\rdk_app_helpers', main: 'd:\\Code\\rdk\\rdk\\app\\example\\web\\scripts\\main' }, //放开这些注释,那将只合并文件而不压缩,可通过这个方法来调试合并后但未被压缩的代码 // uglify2: { // output: { // beautify: true // }, // compress: { // sequences: false, // global_defs: { // DEBUG: false // } // }, // warnings: true, // mangle: false // }, })
import {LanguageContext} from "./LanguageContext"; import React from "react"; class LanguageSwitcher extends Component { render() { return ( <LanguageContext.Consumer> {({ language, setLanguage }) => ( <button onClick={() => setLanguage("jp")}> Switch Language (Current: {language}) </button> )} </LanguageContext.Consumer> ); } }
import React, { Component } from 'react'; import Carousel from '@components/carousel/index'; import Comments from '@components/comments/index'; import Avatar from '@components/avatar/index'; import Style from './index.module.less'; import { inject, observer } from 'mobx-react'; @inject('rootStore') @observer class DynamicList extends Component { topicLikeFn = (likeInfo) => { this.props.rootStore.dataStore.handleTopicLike(likeInfo); }; addCommentsFn = (comment) => { this.props.rootStore.dataStore.addTopicComment(comment); }; topicCollectFn = (collectInfo) => { this.props.rootStore.dataStore.handleTopicCollect(collectInfo); }; render() { return ( <div className={Style['dynamic-list']}> { this.props.rootStore.dataStore.topicList.map((item, index) => { return ( <article className={Style['article']} key={index}> <header className={Style['header']}> <Avatar userInfo={item.userInfo}/> </header> <h3 className={Style['title']}>{item.topic.topicTitle}</h3> <div className={Style['container']}> <Carousel imageList={item.topic.topicImgList}></Carousel> </div> {/* 评论区 */} <div className={Style['comments-content']}> <Comments topicLikeFn={this.topicLikeFn} addCommentsFn={this.addCommentsFn} topicCollectFn={this.topicCollectFn} topicIndex={index} createdAt={item.topic.created_at} discuss={item.discuss} topicId={item.topic.topicId} topicLike={item.topic.topicLike} topicCollect={item.topic.topicCollect} dotCounts={item.topic.topicLikeCounts}> </Comments> </div> </article> ) }) } </div> ); } } export default DynamicList;
let counter=0; function baslat(id){ counter+=1; // document.getElementById("sayac").innerHTML=counter; if(counter<2){ id.innerHTML="STARTED"; myGame() } /*else{ document.getElementById('finish').innerHTML="" }*/ } function myGame(){ const cvs=document.getElementById('game') const ctx=cvs.getContext('2d') const drawRect = (x,y,w,h,color) => { ctx.fillStyle=color ctx.fillRect(x,y,w,h) } const drawCircleF = (x,y,r,color) =>{ ctx.fillStyle=color ctx.beginPath() ctx.arc(x,y,r,0,2*Math.PI,false) //yay çizme ctx.closePath() ctx.fill() } const drawCircleS = (x,y,r,w,color) =>{ ctx.strokeStyle=color ctx.lineWidth=w ctx.beginPath() ctx.arc(x,y,r,0,2*Math.PI,false) //yay çizme ctx.closePath() ctx.stroke() } const drawText = (text,x,y,color) => { ctx.fillStyle=color ctx.font='40px sans-serif' ctx.fillText(text,x,y) } const user={ x:20, y:cvs.height/2-50, w:10, h:100, color:'#fff', score:0 } const computer={ x:cvs.width-30, y:cvs.height/2-50, w:10, h:100, color:'#fff', score:0 } const ball={ x:cvs.width/2, y:cvs.height/2, r:13, color:'#a51890', speed:5, velocityX:3, //dikeydeki hızı velocityY:4 , //yataydaki hızı stop:true //kullanıcı çubuğunu hareket ettirmeden top hareket etmesin } const moveUser=(e)=>{ let rect=cvs.getBoundingClientRect() user.y=e.clientY-rect.top-user.h/2 //e.clientY -> userın Y değeri ball.stop=false } cvs.addEventListener('mousemove',moveUser) const collision=(b,p) =>{ // b:ball, p: player b.top=b.y-b.r b.bottom=b.y+b.r b.left=b.x-b.r b.right=b.x+b.r p.top=p.y p.bottom=p.y+p.h p.left=p.x p.right=p.x+p.w return (b.top<p.bottom && b.bottom>p.top && b.left <p.right && b.right> p.left) } const resetBall = () =>{ ball.x=cvs.width/2 ball.y=cvs.height/2 ball.speed=5 ball.velocityX=3 ball.velocityY=4 ball.stop=true } const update=()=>{ if(!ball.stop){ ball.x+=ball.velocityX ball.y+=ball.velocityY } if(ball.y+ball.r>cvs.height||ball.y-ball.r<0) ball.velocityY=-ball.velocityY let computerLvl=0.1 computer.y+=(ball.y-(computer.y+computer.h/2))*computerLvl let player=(ball.x<cvs.width/2) ? user:computer if(collision(ball,player)){ let intersectY=ball.y-(player.y+player.h/2) intersectY /=player.h/2 let maxBounceRate=Math.PI/3 let bounceAngle=intersectY*maxBounceRate let direction=(ball.x < cvs.width/2) ? 1 : -1 ball.velocityX=direction*ball.speed*Math.cos(bounceAngle) ball.velocityY=ball.speed*Math.sin(bounceAngle) ball.speed+=2 } if(ball.x>cvs.width){ user.score++ resetBall() }else if(ball.x<0) { computer.score++ resetBall() } } const render=()=>{ drawRect(0,0,cvs.width,cvs.height,'green') //#008374 drawRect(cvs.width/2-2,0,4,cvs.height,'#fff') drawCircleF(cvs.width/2,cvs.height/2,8,'#fff') drawCircleS(cvs.width/2,cvs.height/2,50,4,'#fff') drawText(user.score,cvs.width/4,100,'#fff') drawText(computer.score,cvs.width/1.5,100,'#fff') drawRect(user.x,user.y,user.w,user.h,user.color) drawRect(computer.x,computer.y,computer.w,computer.h,computer.color) drawCircleF(ball.x,ball.y,ball.r,ball.color) } //render() const game=()=>{ update() render() } const fps=50 //topun hareket hızı setInterval(game,1000/fps) } /* drawRect(0,0,600,400,'green') drawCircleF(50,50,10,'#fff') drawCircleS(250,250,50,10,'#fff') drawText('deneme',400,200,'#fff')*/
let PokerOtherManager = require("./PokerOtherManager"); let PokerUtil = require("../PokerUtil"); let PokerAnimation = require("../PokerAnimation"); cc.Class({ extends: PokerOtherManager, properties: { SORT_KING: 0, SORT_BOMB: 1, SORT_THREE: 2, SORT_PAIR: 3, POKER_SCALE: 0, CUR_POKER_COUNT: null, OPER_POKER_TAG: 99778866, }, onLoad() { this.CUR_POKER_COUNT = { FOUR: 4, SIX: 6, NINE: 9, TWELVE: 12, FOURTEEN: 14, SIXTEEN: 16, SEVENTEEN: 17, } this.POKER_SCALE = qf.pokerconfig.pokerScale.MAX; this.initDifferent(); }, initDifferent() { this._pokers = []; this._pokersLen = null; // poker的长度 this._leftPosx = null; // 最左边的 this._boundingBox = null; // aabb盒子 this._beganPoint = null; // 鼠标点击的点 this._isDraging = false; // 是否在拖拽 this._dragingCardsNode = null; //拖拽的牌的节点 this._dragingPokers = null; //拖拽牌的对象表 this._clickOIndex = null; // 非标准区域的点击 this._promitIndex = null; // 当前提示到第几个了 this._promitTables = null; // 提示列表 this.tuoguanStatus = false; // 是否是托管狀態 this.canTouch = !this.tuoguanStatus; //牌是不是可以点 this.closeDrag = true; // 关闭拖拽 this.playingAni = false; //发牌动画播放中 this.multiple = true; this.init(); this.handCardsPos = cc.v2(0, 0); }, init() { this.pu = new PokerUtil(); // this.pokerAnimation = new PokerAnimation(); qf.utils.addTouchEvent(this.node, this.touchended.bind(this), this.touchmoved.bind(this), this.touchbegan.bind(this)); }, touchbegan(event) { let touch = event.touch; if (this._pokers.length === 0) return false; // poker为0 let inDeskUser = qf.cache.desk.getOnDeskUserByUin(qf.cache.user.uin); if (!this.canTouch || !inDeskUser) return false; let point = touch.getLocation(); this._beganPoint = point; this._isDraging = false; this._clickOIndex = null; if (this._boundingBox.intersection(point)) { //点击区域在牌内 let index = this.getIndexByPoint(point); if (qf.utils.isValidType(index)) { this._pokers[index].mark(); return true; } } else if ((point.x >= this._leftPosx) //在牌外,检查是否点击了弹出了牌 && (point.x < this._leftPosx + this._pokersLen) && (point.y < this.getUpY() + qf.pokerconfig.pokerInversionDistance * this.POKER_SCALE) && (point.y >= this.getDownY())) { let index = this.getPokerByPoint(point); // 获取点击的牌 if (qf.utils.isValidType(index)) { let index2 = this.getIndexByPoint(point); if (index !== index2) { this._clickOIndex = index; } this._pokers[index].mark(); return true; } } return false; }, touchmoved(event) { if (!this.canTouch) return; let touch = event.touch; let point = touch.getLocation(); if (this.closeDrag) { //拖拽关了 this.updateMarkStatus(point); return; } if (point.y > this.getUpY() + qf.pokerconfig.pokerInversionDistance * this.POKER_SCALE || this._isDraging) { // 被拖出屏幕了,牌跟着走呗 // 先要检查选择之前有没有牌是弹起状态 if (!this._isDraging) { this.genDragingCards(); this._isDraging = true; } this._dragingCardsNode.adjustPoint(point); } else if (!this._isDraging) { //用户在牌内拖来拖去,且不是在外面 this.updateMarkStatus(point); } }, touchended(event) { if (!this.canTouch) return; let touch = event.touch; if (this._isDraging) { //检查mark状态,若是拖动状态 let point = touch.getLocation(); if (this._boundingBox.intersection(point)) { //非法规则直接放回,或者拖到了牌内 this.putDragingCardsToPokers(); } else { // 发送消息打牌,并且返回参数 const isCanSend = (qf.cache.desk.getNextUin() === qf.cache.user.uin) && (qf.cache.desk.getStatus() === qf.const.LordGameStatus.GAME_STATE_INGAME); //先检查自己的状态- 若处理自己出牌阶段 const param = { drag: true, isCanSend: isCanSend }; this.sendCard(param); if (!isCanSend) { //不是你的状态 this.putDragingCardsToPokers(); } } } else { //非拖动状态 let smartTips = true; for (let k in this._pokers) { let v = this._pokers[k]; if (v.isUp) { smartTips = false; break; } } if (smartTips) { /*选之前一个都没选中,那么应该智能提示, 检查选中的中,有没有候选提示方案,如果没有,则全部选中*/ let markCards = []; for (let k in this._pokers) { let v = this._pokers[k]; if (v.isMark) { markCards.push(v.id); } } if (markCards.length <= 0) { smartTips = false; } else if ((qf.cache.desk.getLastCardsNum() === 0)) { // 忽略生成提示的 logd(" ---智能提示啊 ---- "); // v500需求,玩家手动划出的牌全部弹起 smartTips = false; } else { logd(" ---- 从提示列表中寻找候选的 ---- "); //如果找不到 if (this._promitTables && this._promitTables.length !== 0) { let hasCards = false; if (markCards.length > 1) { //判断提示的是选中的子集 let scards = qf.pokerai.getSmartCardsInPromitTable(markCards, this._promitTables, this._pokers); if (scards) { hasCards = true; this.upCards1(qf.pokerai.unSerialization(scards), markCards); this.clearMark(); } } if (!hasCards) { //判断选中的是提示的子集 let scards1 = qf.pokerai.getSmartCardsInPromitTable1(markCards, this._promitTables, this._pokers); if (scards1) { this.upCards1(qf.pokerai.unSerialization(scards1), markCards); this.clearMark(); } else { smartTips = false; } } } else { smartTips = false; } } } let temp_cards = []; if (!smartTips) { for (let k in this._pokers) { let v = this._pokers[k]; if (v.isMark) { v.doInversion(); temp_cards.push(v); } v.unmark(); } } if (temp_cards.length > 1) { this.node.runAction(cc.repeat( cc.sequence( cc.callFunc(() => { MusicPlayer.playMyEffect("xuanpai"); }), cc.delayTime(0.05) ), temp_cards.length > 5 ? 5 : temp_cards.length)) } else if (temp_cards.length === 1) { MusicPlayer.playMyEffect("xuanpai"); } } //到我操作拖牌显示按钮 this.sendInfoToBnt(); }, setCards(pokers) { this.clear(); let count = pokers.length; let pos = this.pokerAnimation.getPos(this.handCardsPos, count, this.POKER_SCALE, 0, true).pos; for (let i in pokers) { let id = pokers[i]; let poker = qf.pokerpool.take({ id: id, resType: qf.const.NEW_POKER_TYPE.NORMAL }); poker.scale = this.POKER_SCALE; poker.x = pos[i].x; poker.y = pos[i].y; poker.parent = this.node; this._pokers.push(poker); } qf.pokerutil.sortPokers(this._pokers); this.updatePokers(); }, updatePokers() { if (this._pokers.length === 0) return; this.cardTypeAutoAdjust(); let count = this._pokers.length; let pos = this.pokerAnimation.getPos(this.handCardsPos, count, this.POKER_SCALE, 0, true).pos; for (let i in this._pokers) { let intI = qf.func.checkint(i) + 1; let poker = this._pokers[i]; poker.x = pos[i].x; poker.y = pos[i].y; poker.setInitDownPosY(pos[i].y); poker.isUp && poker.setUp(); poker.unDizhu(); poker.unCardShow(); poker.zIndex = intI; poker.setColorSpriteShow(false); let curRowNum = Math.floor(intI / qf.pokerconfig.maxRowPokerNum); if ((curRowNum > 0 && intI === curRowNum * qf.pokerconfig.maxRowPokerNum) || intI === count) { poker.setColorSpriteShow(true); } if (qf.cache.desk.isMySelfLand()) { this._pokers[this._pokers.length - 1].setDizhu(0); } let user = qf.cache.desk.getUserByUin(qf.cache.user.uin); if (user && user.show_multi > 1) { this._pokers[this._pokers.length - 1].setCardShow(0); } this.updateBoundingBox(); this.canTouch = !this.tuoguanStatus; } }, cardTypeAutoAdjust() { let twoPokerArr = []; let threePokerArr = []; let fourPokerArr = []; for (let i in this._pokers) { let poker = this._pokers[i]; let intI = qf.func.checkint(i); if (intI === qf.const.CARDTYPEAUTOADJUST_COUNT.NINE) { twoPokerArr.push(poker.id); threePokerArr.push(poker.id); fourPokerArr.push(poker.id); } if (intI === qf.const.CARDTYPEAUTOADJUST_COUNT.TEN) { twoPokerArr.push(poker.id); threePokerArr.push(poker.id); fourPokerArr.push(poker.id); } if (intI === qf.const.CARDTYPEAUTOADJUST_COUNT.ELEVEN) { threePokerArr.push(poker.id); fourPokerArr.push(poker.id); } if (intI === qf.const.CARDTYPEAUTOADJUST_COUNT.TWELVE) { fourPokerArr.push(poker.id); } } if (qf.pokerai.getPA().getCardTypeWithFullId(fourPokerArr) === qf.const.LordPokerType.ZHADAN) { qf.pokerconfig.cardTypeAutoAdjust(qf.const.LordPokerType.ZHADAN); } else if (qf.pokerai.getPA().getCardTypeWithFullId(threePokerArr) === qf.const.LordPokerType.SAN) { qf.pokerconfig.cardTypeAutoAdjust(qf.const.LordPokerType.SAN); } else if (qf.pokerai.getPA().getCardTypeWithFullId(twoPokerArr) === qf.const.LordPokerType.DUIZI) { qf.pokerconfig.cardTypeAutoAdjust(qf.const.LordPokerType.DUIZI); } else { qf.pokerconfig.cardTypeAutoAdjust(-1); } return true; }, getInsertCards(cards) { let pokerTable = []; for (let k in cards) { let v = cards[k]; let bfind = this.findPokerId(v); if (!bfind) { pokerTable.push(v); } } return pokerTable; }, findPokerId(pokerId) { for (let k in this._pokers) { let v = this._pokers[k]; if (v.id === pokerId) { return true; } } return false; }, insertCards(cards) { cards = this.getInsertCards(cards); if (cards.legnth <= 0) return; for (let i in cards) { let card = cards[i]; let poker = qf.pokerpool.take({ id: card, resType: qf.const.NEW_POKER_TYPE.NORMAL }); poker.scale = this.POKER_SCALE; poker.parent = this.node; this._pokers.push(poker); } qf.pokerutil.sortPokers(this._pokers); this.updatePokers(); let hash2 = {}; for (let i in cards) { let card = cards[i]; hash2[card] = true; } for (let i in this._pokers) { let poker = this._pokers[i]; if (hash2[poker.id]) { poker.y = poker.getInitDownPosY(); + qf.pokerconfig.insertPokerUpDistance; poker.stopAllActions(); poker.runAction(cc.sequence( cc.delayTime(qf.pokerconfig.insertPokerDelayTime), cc.moveTo(qf.pokerconfig.insertPokerMoveTime, cc.v2(poker.x, poker.getInitDownPosY())), cc.callFunc(() => { if (qf.cache.desk.getIsUserAutoPlay(qf.cache.user.uin)) { this.allMark(); } }) )) } } }, removeCard() { let pokers = []; for (let i in this._pokers) { if (this._pokers[i]) { pokers.push(this._pokers[i]); } } this._pokers = pokers; this.updatePokers(); }, removeCardsByIndex(index) { for (let k in index) { let v = index[k]; this._pokers[v].clear(); this._pokers[v] = null; } this.removeCard(); }, genDragingCards() { let dragingIndexs = []; for (let k in this._pokers) { //先判断有没有选牌 let v = this._pokers[k]; if (v.isUp) { dragingIndexs.push(k); } } if (dragingIndexs.length === 0) { for (let k in this._pokers) { let v = this._pokers[k]; if (v.isMark) { dragingIndexs.push(k); } } } this.clearMark(); if (dragingIndexs.length !== 0) { //重新设置牌,且重新 this._dragingCardsNode = new cc.Node(); this._dragingCardsNode.parent = this.node; this._dragingCardsNode.zIndex = qf.pokerconfig.otherZ; this._dragingPokers = []; for (let k in dragingIndexs) { let v = dragingIndexs[k]; let p = this._pokers[v]; this._pokers[v] = null; this._dragingPokers[k] = { poker: p, index: v }; p.parent = this._dragingCardsNode; p.unDizhu(); p.unCardShow(); let i = qf.func.checkint(k); if ((i === dragingIndexs.length - 1) && qf.cache.desk.isMySelfLand()) { p.setDizhu(0); // 打出的牌设置地主标志 } } this._dragingCardsNode.offsetx = qf.pokerutil.getPokerLen(dragingIndexs.length) / 2; //设置呗 this._dragingCardsNode.offsety = this.handCardsPos.y; this._dragingCardsNode.adjustPoint = (point) => { this.setPosition(cc.v2(point.x - 0.5 * this.offsetx, point.y - 0.5 * this.offsety)); } this.removeCard(); } }, putDragingCardsToPokers() { for (let k in this._dragingPokers) { let v = this._dragingPokers[k]; let poker = v.poker; poker.isUp = true; let len = this._pokers.length; for (let i = len - 1; i >= 0; i--) if (i === v.index) { this._pokers[i + 1] = this._pokers[i]; this._pokers[i] = poker; } else if (i > v.index) { this._pokers[i + 1] = this._pokers[i]; } poker.parent = this.node; } this.updatePokers(); this._dragingCardsNode.parent = null; this._dragingCardsNode = null; this._dragingPokers = null; }, updateBoundingBox() { this._pokersLen = qf.pokerutil.getPokerLen(this._pokers.length) * this.POKER_SCALE; this._leftPosx = -this._pokersLen / 2; let height = 0; let row = Math.ceil((this._pokers.length - 1) / qf.pokerconfig.maxRowPokerNum); if (this._pokers.length > 0) { height = (qf.pokerconfig.pokerHeight + row * qf.pokerconfig.pokerSpace[0].height) * this.POKER_SCALE; } this._boundingBox = cc.rect(this._leftPosx, this.getDownY(), this._pokersLen, height); }, getUpY() { let row = Math.floor((this._pokers.length - 1) / qf.pokerconfig.maxRowPokerNum); return (qf.pokerconfig.pokerHeight + row * qf.pokerconfig.pokerSpace[0].height) * 0.5 * this.POKER_SCALE; }, getDownY() { let row = Math.floor((this._pokers.length - 1) / qf.pokerconfig.maxRowPokerNum); return -(qf.pokerconfig.pokerHeight + row * qf.pokerconfig.pokerSpace[0].height) * this.POKER_SCALE / 2; }, clear() { this.clearNoPokerThanOther(); this.removeTuoGuan(); for (let k in this._pokers) { let v = this._pokers[k]; if (v) { v.clear(); } } this._pokers = []; qf.pokerpool.initPool(); this.updateBoundingBox(); this.playingAni = false; }, getIndexByPoint(point) { for (let i = this._pokers.length - 1; i >= 0; i--) { let v = this._pokers[i]; if ((point.x >= -qf.pokerconfig.pokerWidth * this.POKER_SCALE / 2) && (point.x < qf.pokerconfig.pokerWidth * this.POKER_SCALE / 2) && (point.y >= -qf.pokerconfig.pokerHeight * this.POKER_SCALE / 2) && (point.y < qf.pokerconfig.pokerHeight * this.POKER_SCALE / 2)) { return i; } } }, getPokerByPoint(point) { for (let i = this._pokers.length - 1; i >= 0; i--) { let v = this._pokers[i]; if ((point.x >= v.x - qf.pokerconfig.pokerWidth * this.POKER_SCALE / 2) && (point.x < v.x + qf.pokerconfig.pokerWidth * this.POKER_SCALE / 2) && (point.y >= v.y - qf.pokerconfig.pokerHeight * this.POKER_SCALE / 2) && (point.y < v.y + qf.pokerconfig.pokerHeight * this.POKER_SCALE / 2) && (v.isUp)) { return i; } } return null; }, updateMarkStatus(point) { let bpoint = this._beganPoint; if (qf.utils.isValidType(this._clickOIndex)) { //修复非标准区域的选择问题 bpoint.x = (this._clickOIndex + 0.5) * qf.pokerconfig.pokerDistance; } // 检查区间 let number = this._pokers.length; let beginIndex = this.getIndexByPoint(bpoint); let endIndex = this.getIndexByPoint(point); if (!((beginIndex !== null) && (endIndex !== null))) return; if (beginIndex > endIndex) { let tempIndex = endIndex; endIndex = beginIndex; beginIndex = tempIndex; } for (let i = 0; i < number; i++) { if (i >= beginIndex && i <= endIndex) { this._pokers[i].mark(); } else { this._pokers[i].unmark(); } } }, sendInfoToBnt() { qf.utils.targetStopDelayRun(this, this.OPER_POKER_TAG); qf.utils.targetDelayRun(this, qf.pokerconfig.pokerInversionTime * 1.5, () => { if (this.checkIsCanOperate()) { this.updateOperBtns(); // 更新btn信息 } }, this.OPER_POKER_TAG); }, checkIsCanOperate() { let isCanOperate = false; if ((qf.cache.desk.getStatus() === qf.const.LordGameStatus.GAME_STATE_INGAME) && (qf.cache.desk.getNextUin() === qf.cache.user.uin) && (qf.cache.desk.getShortOpFlag() !== qf.const.OP_FLAG.SHORT) && (!qf.cache.desk.getIsUserAutoPlay(qf.cache.user.uin))) { isCanOperate = true; } return isCanOperate; }, updateOperBtns() { let advanceOutCards = []; for (let k in this._pokers) { let v = this._pokers[k]; if (v.isUp) { advanceOutCards.push(v.id); } } let isBtnShow = qf.const.OPER_BTN_STAUTS.SHOW; let isBtnUnShow = qf.const.OPER_BTN_STAUTS.UNSHOW; let isBtnUnAble = qf.const.OPER_BTN_STAUTS.UNABLE; let bShowBuYao = false; let btnBuYaoStatus = isBtnUnAble; let lastCards = qf.cache.desk.getLastCards(); if (lastCards.length > 0) { bShowBuYao = true; btnBuYaoStatus = isBtnShow; } let cObj = qf.pokerai.checkCanSendCards(advanceOutCards, lastCards, (qf.pokerai.getLaiziHash2(lastCards, qf.cache.desk.getLastCards2())).length); let ret = cObj.isCanSend; if (ret) { if (qf.cache.user.uin === qf.cache.desk.getLordUin() && qf.cache.desk.getLordFirstHandle()) { let user = qf.cache.desk.getUserByUin(qf.cache.user.uin); loge(user) if (user && user.show_multi > 1) { this.node.emit(qf.ekey.DDZ_PM_UPDATEOPERBTNS, [ [0, isBtnUnShow], [1, isBtnUnShow], [2, isBtnUnShow], [3, isBtnUnShow], [4, isBtnUnShow], [5, isBtnUnShow], [6, isBtnShow] ]); } else { this.node.emit(qf.ekey.DDZ_PM_UPDATEOPERBTNS, [ [0, isBtnUnShow], [1, isBtnUnShow], [2, isBtnUnShow], [3, isBtnUnShow], [4, isBtnShow], [5, isBtnShow], [6, isBtnUnShow] ]); } } else { this.node.emit(qf.ekey.DDZ_PM_UPDATEOPERBTNS, [ [0, btnBuYaoStatus], [1, isBtnShow], [2, isBtnShow], [3, isBtnUnShow], [4, isBtnUnShow], [5, isBtnUnShow], [6, isBtnUnShow] ]); } } else { if (qf.cache.user.uin === qf.cache.desk.getLordUin() && qf.cache.desk.getLordFirstHandle()) { let user = qf.cache.desk.getUserByUin(qf.cache.user.uin); loge(user) if (user && user.show_multi > 1) { this.node.emit(qf.ekey.DDZ_PM_UPDATEOPERBTNS, [ [0, isBtnUnShow], [1, isBtnUnShow], [2, isBtnUnShow], [3, isBtnUnShow], [4, isBtnUnShow], [5, isBtnUnShow], [6, isBtnUnAble] ]); } else { this.node.emit(qf.ekey.DDZ_PM_UPDATEOPERBTNS, [ [0, isBtnUnShow], [1, isBtnUnShow], [2, isBtnUnShow], [3, isBtnUnShow], [4, isBtnUnAble], [5, isBtnShow], [6, isBtnUnShow] ]); } } else { this.node.emit(qf.ekey.DDZ_PM_UPDATEOPERBTNS, [ [0, btnBuYaoStatus], [1, isBtnShow], [2, isBtnUnAble], [3, isBtnUnShow], [4, isBtnUnShow], [5, isBtnUnShow], [6, isBtnUnShow] ]); } } this.node.emit(qf.ekey.DDZ_PM_SETIMGNOLARGER, false); }, clearMark() { for (let k in this._pokers) { this._pokers[k].unmark(); } }, allMark() { for (let i in this._pokers) { let poker = this._pokers[i]; poker.mark(); } }, noPokerThanOther() { this.canTouch = false; this.allPokerSetDown(); this.allMark(); }, clearNoPokerThanOther() { if (!this.tuoguanStatus) { this.clearMark(); this.canTouch = !this.tuoguanStatus; } }, pokerNotRight(drag) { if (!drag) { this.allPokerSetDown(); let isBtnShow = qf.const.OPER_BTN_STAUTS.SHOW; let isBtnUnShow = qf.const.OPER_BTN_STAUTS.UNSHOW; let isBtnUnAble = qf.const.OPER_BTN_STAUTS.UNABLE; this.node.emit(qf.ekey.DDZ_PM_UPDATEOPERBTNS, [ [0, isBtnShow], [1, isBtnShow], [2, isBtnUnAble], [3, isBtnUnShow] ]); this.node.emit(qf.ekey.DDZ_PM_SETIMGNOLARGER, false); } }, allPokerPushDown() { for (let k in this._pokers) { let v = this._pokers[k]; if (v.isUp) { v.doInversion(); } } }, allPokerSetDown() { for (let k in this._pokers) { let v = this._pokers[k]; v.setDown(); } }, allPokerSetUp() { for (let k in this._pokers) { let v = this._pokers[k]; v.setUp(); } }, isValueChecked(card, cards) { for (let k in cards) { let curCard = cards[k]; if (curCard === card) { //在数组中 return true; } } return false; }, getCardsByType(cards, type) { let sameValueCardsLength = 1; let curTypeCards = []; if (type === this.SORT_KING) { // 检查双王 let pushCardsNums = 0; for (let k in cards) { let curCard = cards[k]; let curCardValue = Math.floor(curCard / 4) + 3; if (curCardValue === 17) { //大王 curTypeCards.push(curCard); pushCardsNums = pushCardsNums + 1; } else if (curCardValue === 16) { //小王 curTypeCards.push(curCard); pushCardsNums = pushCardsNums + 1; } } if (pushCardsNums === 2) { return curTypeCards; } else { return []; } } else if (type === this.SORT_BOMB) //检查有炸弹 { sameValueCardsLength = 4; } else if (type === this.SORT_THREE) //检查是否3带 { sameValueCardsLength = 3; } else if (type === this.SORT_PAIR) //检查是对子 { sameValueCardsLength = 2; } curTypeCards = []; for (let i in cards) { let curCheckCard = cards[i]; if (this.isValueChecked(curCheckCard, curTypeCards)) //当前要检查的值已经 在点数一样的列表里 { } else { let curCheckCardValue = Math.floor(curCheckCard / 4) + 3; let sameValeNums = 0; let sameValeCards = []; for (let k in cards) { let curCard = cards[k]; let curCardValue = Math.floor(curCard / 4) + 3; if (curCheckCardValue === curCardValue) { sameValeNums = sameValeNums + 1; sameValeCards.push(curCard); } } if (sameValeNums === sameValueCardsLength) { for (let k in sameValeCards) { let sameCard = sameValeCards[k]; curTypeCards.push(sameCard); } } } } return curTypeCards; }, getSortCardsWithType(nowcards) { if (nowcards && nowcards.length > 0) nowcards.sort(qf.utils.compareNumByDes); let newcards = []; let sortTypes = [this.SORT_KING, this.SORT_BOMB, this.SORT_THREE, this.SORT_PAIR]; for (let i in sortTypes) { let type = sortTypes[i]; let curTypeCards = this.getCardsByType(nowcards, type); for (let k in curTypeCards) { let sameCard = curTypeCards[k]; newcards.push(sameCard); } } for (let k in nowcards) { let card = nowcards[k]; if (this.isValueChecked(card, newcards)) //已经在 四个牌型的列表中 { } else //不在四个牌型的列表中 加上 { newcards.push(card); } } return newcards; }, sendCard(paras) { if (!paras.isCanSend) { logd(" ----- --不能出牌,不是出牌阶段 "); return; } let nowcards = []; let nowcardsNode = []; if (paras.drag) { for (let k in this._dragingPokers) { let v = this._dragingPokers[k]; nowcards.push(v.poker.id); nowcardsNode.push(v.poker); } } else { for (let k in this._pokers) { let v = this._pokers[k]; if (v.isUp) { nowcards.push(v.id); nowcardsNode.push(v); } } } nowcards = this.getSortCardsWithType(nowcards); qf.event.dispatchEvent(qf.ekey.LORD_NET_DISCARD_REQ, { card: nowcards, cards2: [] }) // 发送给服务器 }, genPromitTable() { let cards = []; for (let k in this._pokers) { let v = this._pokers[k]; cards.push(v.id); } this._promitTables = qf.pokerai.promit(cards, qf.cache.desk.getLastCards(), (qf.pokerai.getLaiziHash2(qf.cache.desk.getLastCards(), qf.cache.desk.getLastCards2())).length); this._promitIndex = 0; return this._promitTables.length; }, promit() { if (!this._promitTables) { this.genPromitTable(); } if (this._promitTables.length === 0) { //没有提示,点提示按钮就不出 this.node.emit(qf.ekey.DDZ_PM_DONTSENDCARD) return; } let upcards = qf.pokerai.unSerialization(this._promitTables[this._promitIndex]); this._promitIndex = this._promitIndex + 1; if (this._promitIndex > this._promitTables.length - 1) { this._promitIndex = 0; } this.upCards(upcards); }, upCards(upcards) { for (let k in this._pokers) { let v = this._pokers[k]; let id = Math.floor(v.id / 4) + 3; if (upcards[id] && (upcards[id] > 0)) { //这些要弹起 upcards[id] = upcards[id] - 1; v.markUp = true; if (!v.isUp) { v.doInversion(); } } else { //这些要坐下 if (v.isUp) { v.markDown = true; } } } let number = 0; for (let k in upcards) { let v = upcards[k]; number = number + v; } for (let k in this._pokers) { let v = this._pokers[k]; if (v.laizi && (number > 0) && (!v.markUp)) { number = number - 1; if (!v.isUp) { v.doInversion(); } v.markDown = false; } } for (let k in this._pokers) { let v = this._pokers[k]; v.markUp = null; if (v.markDown) { v.setDown(); v.markDown = false; } } this.sendInfoToBnt(); }, //开始 upCards1(upcards, markCards) { let realCards = this.getRealUpCards(upcards, markCards); for (let k in this._pokers) { let v = this._pokers[k]; let id = Math.floor(v.id / 4) + 3; if (upcards[id] && (upcards[id] > 0)) { //这些要弹起 if (realCards[id]) { let has = false; for (let j in realCards[id]) { if (realCards[id][j] === v.id) { has = true; break; } } if (has) { upcards[id] = upcards[id] - 1; v.markUp = true; if (!v.isUp) { v.doInversion(); } } else { //这些要坐下 if (v.isUp) { v.markDown = true; } } } else { upcards[id] = upcards[id] - 1; v.markUp = true; if (!v.isUp) { v.doInversion(); } } } else { //这些要坐下 if (v.isUp) { v.markDown = true; } } } let number = 0; for (let k in upcards) { let v = upcards[k]; number = number + v; } for (let k in this._pokers) { let v = this._pokers[k]; if (v.laizi && (number > 0) && (!v.markUp)) { number = number - 1; if (!v.isUp) { v.doInversion(); } v.markDown = false; } } for (let k in this._pokers) { let v = this._pokers[k]; v.markUp = null; if (v.markDown) { v.setDown(); v.markDown = false; } } this.sendInfoToBnt(); }, getRealUpCards(upcards, markCards) { let allCards = {}; for (let k in this._pokers) { let v = this._pokers[k]; let id = Math.floor(v.id / 4) + 3; if (!allCards[id]) { allCards[id] = []; } allCards[id].push(v.id); } let mcards = {}; for (let k in markCards) { let v = markCards[k]; let id = Math.floor(v / 4) + 3; if (upcards[id] && (upcards[id] > 0)) { if (!mcards[id]) { mcards[id] = []; } mcards[id].push(v); } } let realCards = {}; for (let k in allCards) { let v = allCards[k]; let id = k; if (upcards[id] && (upcards[id] > 0) && (v.length > upcards[id])) { if (mcards[id] && mcards[id].length > 0 && upcards[id] >= mcards[id].length) { let card_ = this.getCardsByNum(v, upcards[id], mcards[id]); if (card_ && card_.length > 0) { realCards[id] = card_; } } } } return realCards; }, getCardsByNum(cards, unum, mcards) { let sortCards = []; //得到sortCards:[4,5],[5,6],[6,7],[7,8] for (let i = 0; i < cards.length; i++) { let num = 0; let k = i; let scards = []; for (let j = k; j < cards.length; j++) { scards.push(cards[j]); num = num + 1; if (num === unum) { sortCards.push(scards); break; } } } //得到sortCards:[4,5] for (let i = 0; i < sortCards.length; i++) { let v = sortCards[i]; let isMatch = false; for (let j = 0; j < mcards.length; j++) { let m = mcards[j]; let isMatch0 = false; for (let k = 0; k < v.length; k++) { if (m === v[k]) { isMatch0 = true; } } if (!isMatch0) { isMatch = false; break; } else { isMatch = true; } } if (isMatch) { return v; } } }, clearPromit() { this._promitTables = null; }, getSelectCards() { let result = {}; let sel = []; let index = []; for (let k in this._pokers) { let v = this._pokers[k]; if (v.isUp) { sel.push(v.id); index.push(k); } } result.sel = sel; result.index = index; return result; }, sendCardAnimationsByDrag(type, laizicards) { let cardNodes = []; let allpos = []; for (let k in this._dragingPokers) { let v = this._dragingPokers[k]; let poker = v.poker; cardNodes.push(poker); allpos.push(poker.convertToWorldSpace(cc.v2(0, 0))); } this.changLaiziToDestValue(cardNodes, laizicards); this.pokerAnimation.sendCardByDrag(cardNodes, type, allpos, this._dragingCardsNode.getPosition()); this._dragingCardsNode.parent = null; this._dragingCardsNode = null; this._dragingPokers = null; }, sendCardAnimations(paras) { if (!paras.laizicards) { paras.laizicards = []; } let type1 = null; if (qf.utils.isValidType(paras.ctype)) { type1 = paras.ctype; } else { if (paras.laizicards.length <= 0) { type1 = qf.pokerai.getCardTypeWithFullId(paras.cards); } else { type1 = qf.pokerai.getCardTypeWithFullId(paras.laizicards); } } let laizicards = paras.laizicards; logd(" ----------------出牌 -----" + type1); if (paras.drag) { qf.cache.desk.setIsUserSendCard(true); this.sendCardAnimationsByDrag(type1, laizicards); return; } //如果癞子有牌,则代表 let cardNodes = []; paras.cards = this.getSortCardsWithType(paras.cards); if (paras.index === 0 && paras.uin === qf.cache.user.uin) { if (paras.reconnect) { //断线重连的,直接显示 let count = paras.cards.length; for (let k in paras.cards) { let i = qf.func.checkint(k) + 1; let v = paras.cards[k]; cardNodes[k] = qf.pokerpool.take({ id: v, resType: qf.const.NEW_POKER_TYPE.NORMAL }); cardNodes[k].scale = this.POKER_SCALE; cardNodes[k].setColorSpriteShow(false); let curRowNum = Math.floor(i / qf.pokerconfig.maxRowPokerNum); if (curRowNum > 0 && i === curRowNum * qf.pokerconfig.maxRowPokerNum) cardNodes[k].setColorSpriteShow(true); if (i === count) cardNodes[k].setColorSpriteShow(true); } this.pokerAnimation.sendCard0WithReconnect(cardNodes); return; } if (qf.cache.desk.getIsUserSendCard()) { return; } cardNodes = paras.cardsNode; let needFind = false; if (!cardNodes) { //说明托管出牌,需要到牌堆里面去找 cardNodes = []; needFind = true; } let cardHash1 = []; for (let k in paras.cards) { let v = paras.cards[k]; cardHash1.push(v); } for (let i in cardHash1) { let id = cardHash1[i]; for (let k in this._pokers) { let v = this._pokers[k]; if (v && v.id === id) { v.unDizhu(); v.unCardShow(); let pos = cc.v2(v.x, v.y); v.worldPosition = v.parent.convertToWorldSpace(pos); v.unmark(); if (needFind) { cardNodes.push(v); } this._pokers[k] = null; //mark } } } cardHash1 = []; this.removeCard(); //清理牌 qf.cache.desk.setIsUserSendCard(true); } else { for (let k in paras.cards) { let v = paras.cards[k]; let poker = qf.pokerpool.take({ id: v, resType: qf.const.NEW_POKER_TYPE.NORMAL }); cardNodes.push(poker); poker.opacity = 0; poker.scale = this.POKER_SCALE; } } this.changLaiziToDestValue(cardNodes, laizicards); if (cardNodes.length === 0) { return; } if (paras.land) { cardNodes[cardNodes.length - 1].setDizhu(0); } else if ((paras.index === 0) && (qf.cache.desk.isMySelfLand())) { cardNodes[cardNodes.length - 1].setDizhu(0); } if ((paras.uin === qf.cache.user.uin) || paras.isShowCards) { let user = qf.cache.desk.getUserByUin(qf.cache.user.uin); if (user && user.show_multi > 1) cardNodes[cardNodes.length - 1].setCardShow(0); } //设置牌中心图标显示 let count = cardNodes.length; for (let k in cardNodes) { let poker = cardNodes[k]; let i = qf.func.checkint(k) + 1; poker.setColorSpriteShow(false); let curRowNum = Math.floor(i / qf.pokerconfig.maxRowPokerNum); if (curRowNum > 0 && i === curRowNum * qf.pokerconfig.maxRowPokerNum) poker.setColorSpriteShow(true); if (i === count) poker.setColorSpriteShow(true); } this.pokerAnimation.sendCard(cardNodes, type1, paras.index, paras.uin, paras.notShowAction); }, changLaiziToDestValue(cardNodes, _laizicards) { for (let k in cardNodes) { let v = cardNodes[k]; if ((Math.floor(v.id / 4) + 3) === qf.cache.desk.getLaiziPoint()) { v.setLaizi(true); } } let cards = []; for (let k in cardNodes) { let v = cardNodes[k]; cards.push(v.id); } let laizicards = qf.pokerai.getLaiziHash2(cards, _laizicards); if (laizicards.length !== 0) { let laiziindex = 0; for (let k in cardNodes) { let v = cardNodes[k]; if ((v.laizi === true) && (laizicards.length >= laiziindex)) { let to = laizicards[laiziindex]; laiziindex = laiziindex + 1; v.id = qf.pokerconfig.shortIDToLong(to); } } } for (let k in cardNodes) { let v = cardNodes[k]; let zOrder = qf.func.checkint(k) + 1; v.zIndex = zOrder; } }, clearDeskCard(index) { this.pokerAnimation.clearCards(index); }, clearAllDeskCards() { for (let index = 0; index <= 2; index++) { this.pokerAnimation.clearCards(index); } }, // getPokerAnimation() { // return this.pokerAnimation; // }, addTuoGuan() { this.tuoguanStatus = true; this.canTouch = !this.tuoguanStatus; this.node.emit(qf.ekey.DDZ_PM_HINDALLBTNS); this.node.emit(qf.ekey.DDZ_PM_SETIMGNOLARGER, false); this.refreshPokers(); this.allPokerSetDown(); this.allMark(); }, refreshPokers() { if (!this.playingAni) { return; } this.setCards(qf.cache.desk.getMyHandCards()); }, removeTuoGuan() { this.tuoguanStatus = false; this.canTouch = !this.tuoguanStatus; this.clearMark(); }, checkMyHandCards() { let tmpcards = []; for (let k in this._pokers) { let v = this._pokers[k]; tmpcards.push(v.id); } qf.cache.desk.getMyHandCards().sort((a, b) => { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } }); tmpcards.sort((a, b) => { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } }); let cardIsRight = true; if (qf.cache.desk.getMyHandCards().length !== this._pokers.length) { cardIsRight = false; } else { let handTable = qf.cache.desk.getMyHandCards(); for (let k in handTable) { let v = handTable[k]; if (v !== tmpcards[k]) { cardIsRight = false; break; } } } if (!cardIsRight) { logd(" ----- 牌不對,需要同步牌 ----- "); this.setCards(qf.cache.desk.getMyHandCards()); this.setLaizi(); if (this.tuoguanStatus) { this.addTuoGuan(); } this.clearDeskCard(0); } else if (cardIsRight) { logd(" ----- 牌与服务器相同,不需要同步牌 ----- "); } }, setCardsWithAnimations(cards, panel) { this.clear(); this.canTouch = false; this.playingAni = true; let total = cards.length; let objPos = this.pokerAnimation.getPos(this.handCardsPos, total, this.POKER_SCALE, 0, true); let ppp = objPos.pos; for (let k in cards) { let i = qf.func.checkint(k) + 1; let v = cards[k]; let p = qf.pokerpool.take({ id: v, resType: qf.const.NEW_POKER_TYPE.NORMAL }); p.scale = this.POKER_SCALE; p.x = ppp[k].x; p.y = ppp[k].y; p.active = false; p.parent = this.node; this._pokers[k] = p; p.setColorSpriteShow(false); let curRowNum = Math.floor(i / qf.pokerconfig.maxRowPokerNum); if (curRowNum > 0 && i === curRowNum * qf.pokerconfig.maxRowPokerNum) p.setColorSpriteShow(true); if (i === total) p.setColorSpriteShow(true); } let time = 0; let battle_type = qf.cache.desk.getBattleType(); if (battle_type === qf.const.BATTLE_TYPE_UNSHUFFLE) { //不洗牌玩法 time = this.setAnimationWithNoShuffle(objPos, panel); } else { time = this.setAnimation(objPos); } return time; }, setAnimation(objPos) { let total = this._pokers.length; let time = 0; let delayIntervTime = 0.15; let moveTime = 0.4; this.stopPokersAllAcitons(); let count = 0; let multiple; let user = qf.cache.desk.getUserByUin(qf.cache.user.uin); for (let i in this._pokers) { let v = this._pokers[i]; let k = qf.func.checkint(i) + 1; ((v, k) => { v.runAction(cc.sequence( cc.delayTime(delayIntervTime * k), cc.callFunc(() => { v.setVisible(true); count++; if (this.multiple && user && user.show_multi === 1) { if (count > this.CUR_POKER_COUNT.SIXTEEN) { qf.event.dispatchEvent(qf.ekey.HIDE_ALL_BTNS); } else { if (count <= this.CUR_POKER_COUNT.SIX) multiple = qf.const.SHOW_CARD_MULTIPLE.FOUR; if (count > this.CUR_POKER_COUNT.SIX && count <= this.CUR_POKER_COUNT.TWELVE) multiple = qf.const.SHOW_CARD_MULTIPLE.THREE; if (count > this.CUR_POKER_COUNT.TWELVE && count <= this.CUR_POKER_COUNT.FOURTEEN) multiple = qf.const.SHOW_CARD_MULTIPLE.TWO; qf.event.dispatchEvent(qf.ekey.UPDATE_SHOW_CARD_BTN, { multiple: multiple }); } } if (k === total) { this.updateMultiple(true); this.stopPokersAllAcitons(); this.node.runAction(cc.sequence(cc.delayTime(0.1), cc.callFunc(() => { this.actSecond(moveTime, objPos); }))); } }) )) })(v, k); } time = total * delayIntervTime + moveTime + 0.1; return time; }, setAnimationWithNoShuffle(objPos, panel) { let total = this._pokers.length; let delayIntervTime = 0.05; let _time = 0.15; let moveTime = 0.4; this.stopPokersAllAcitons(); let shufflePanel = panel; let shuffleNodes = cc.find("node_shuffles", shufflePanel); shufflePanel.active = true; let count = 0; let multiple; let user = qf.cache.desk.getUserByUin(qf.cache.user.uin); let num = 6; let intervalTime = 0.4; for (let i in this._pokers) { let v = this._pokers[i]; let k = qf.func.checkint(i) + 1; let shuffle = new cc.Node(); shuffle.addComponent(cc.Sprite); shuffle.parent = shuffleNodes; shuffle.getComponent(cc.Sprite).spriteFrame = qf.rm.getSpriteFrame(qf.res.poker, qf.tex.poker_bg_big1); ((v, k, shuffle) => { //自己 let pos_0 = v.parent.convertToWorldSpace(cc.v2(v.x, v.y)); let pos = shuffleNodes.convertToNodeSpace(pos_0); shuffle.runAction(cc.sequence( cc.delayTime(delayIntervTime * k + Math.floor((k - 1) / num) * intervalTime), cc.spawn( cc.moveTo(_time, pos), cc.scaleTo(_time, 1) ), cc.callFunc(() => { v.active = true; count++; if (this.multiple && user && user.show_multi === 1) { if (count >= this.CUR_POKER_COUNT.SEVENTEEN) { qf.event.dispatchEvent(qf.ekey.HIDE_ALL_BTNS); } else { if (count <= this.CUR_POKER_COUNT.SIX) multiple = qf.const.SHOW_CARD_MULTIPLE.FOUR; if (count > this.CUR_POKER_COUNT.SIX && count <= this.CUR_POKER_COUNT.TWELVE) multiple = qf.const.SHOW_CARD_MULTIPLE.THREE; if (count > this.CUR_POKER_COUNT.TWELVE && count <= this.CUR_POKER_COUNT.SEVENTEEN) multiple = qf.const.SHOW_CARD_MULTIPLE.TWO; qf.event.dispatchEvent(qf.ekey.UPDATE_SHOW_CARD_BTN, { multiple: multiple }); } } if (shuffle) { shuffle.parent = null; } if (k === total) { this.updateMultiple(true); this.stopPokersAllAcitons(); this.node.runAction(cc.sequence(cc.delayTime(0.1), cc.callFunc(() => { this.actSecond(moveTime, objPos); }))); } }) )); })(v, k, shuffle); } let time = total * delayIntervTime + Math.floor((total - 1) / num) * intervalTime + _time + moveTime + 0.1; return time; }, updateMultiple(value) { this.multiple = value; }, stopPokersAllAcitons() { for (let k in this._pokers) { let v = this._pokers[k]; v.stopAllActions(); } let battle_type = qf.cache.desk.getBattleType(); if (battle_type === qf.const.BATTLE_TYPE_UNSHUFFLE) { //不洗牌玩法 this.node.emit(qf.ekey.DDZ_PM_SHUFFLEPANELHIDE); } }, stopSendPokersAcitons() { this.updateMultiple(true); this.stopPokersAllAcitons(); this.playingAni = false; let cards = qf.cache.desk.getMyHandCards(); if (!cards) { cards = []; } if (cards && cards.length > 0) { this.setCards(cards); } }, actSecond(moveTime, objPos) { let total = this._pokers.length; let objFinalPos = this.pokerAnimation.getPos(this.handCardsPos, total, this.POKER_SCALE, 0, true, true); let finalPos = null; if (objPos) { finalPos = objPos.pos; } else { finalPos = objFinalPos.pos; } let objStartPos = this.pokerAnimation.getPos(this.handCardsPos, total, this.POKER_SCALE, 0, true, true); qf.pokerutil.sortPokers(this._pokers); this.updatePokers(); for (let i in this._pokers) { let v = this._pokers[i]; let k = qf.func.checkint(i); ((v, k) => { v.runAction(cc.sequence( cc.moveTo(moveTime, this.getHandCardsPos()), cc.callFunc(() => { let zOrder = k; v.zIndex = zOrder; }), cc.moveTo(moveTime, cc.v2(finalPos[k].x, finalPos[k].y)), cc.callFunc((sender) => { if (k + 1 === total) { logd("sendPokerFinished2"); this.updatePokers(); this.playingAni = false; } }) )); })(v, k); } }, showLastAllCards(cards, index, parentNode) { if (cards.length <= 0) return; let cardNodes = []; for (let k in cards) { let v = cards[k]; let p = qf.pokerpool.take({ id: v, resType: qf.const.NEW_POKER_TYPE.NORMAL }); p.scale = this.POKER_SCALE; if ((Math.floor(v / 4) + 3) === qf.cache.desk.getLaiziPoint()) { p.setLaizi(true); } cardNodes.push(p); } qf.pokerutil.sortPokers(cardNodes); let total = cardNodes.length; for (let k in cardNodes) { let i = qf.func.checkint(k) + 1; let p = cardNodes[k]; p.setColorSpriteShow(false); let curRowNum = Math.floor(i / qf.pokerconfig.maxRowPokerNum); if (curRowNum > 0 && i === curRowNum * qf.pokerconfig.maxRowPokerNum) p.setColorSpriteShow(true); if (i === total) p.setColorSpriteShow(true); } if (index === 0) { this.pokerAnimation.showLastAnimation(cardNodes, index, parentNode, true); this.clear(); } else if (index === 1) { this.pokerAnimation.showLastAnimation(cardNodes, index, parentNode, true); } else if (index === 2) { this.pokerAnimation.showLastAnimation(cardNodes, index, parentNode, true); } }, setLaizi() { qf.pokerai.laizi = null; let laiziPoint = qf.cache.desk.getLaiziPoint(); if (!laiziPoint) { return; } if (laiziPoint <= 2) { return; } qf.pokerai.laizi = laiziPoint; for (let k in this._pokers) { let v = this._pokers[k]; if ((Math.floor(v.id / 4) + 3) === laiziPoint) { v.setLaizi(true); } } qf.pokerutil.sortPokers(this._pokers); this.updatePokers(); }, clearLaizi() { qf.pokerai.laizi = null; }, getHandCardsPos() { return this.handCardsPos; }, updateShowCard(cards) { this.setCards(cards); }, setAllPokerDownByClick() { if (this._pokers.length === 0) { return; } let inDeskUser = qf.cache.desk.getOnDeskUserByUin(qf.cache.user.uin); if (!this.canTouch || !inDeskUser) { return; } logd("-----------------setAllPokerDownByClick-----------------"); this.allPokerSetDown(); this.sendInfoToBnt(); }, setLastCardsAuto() { this.canTouch = false; this.allPokerSetDown(); } })
console.log("Hello Ayush");
!(function (t) { "use strict"; $(document).ready(function () { var table_companies = $("#table_planning_prod").dataTable({ bStateSave: false, ajax: "module/planning/table/php/data_liste_planning.php?job=get_liste_planning", columns: [ { data: "Livrable", sClass: "" }, { data: "Code_GMOD_P", sClass: "" }, { data: "Technicien", sClass: "" }, { data: "MARQUE", sClass: "" }, { data: "GMOD_P", sClass: "" }, { data: "Statut", sClass: "" }, { data: "Date_insertion", sClass: "" }, { data: "bouton_1", sClass: "" }, ], dom: "Bfrtip", colReorder: true, language: { sEmptyTable: "Aucune donnée disponible dans le tableau", sInfo: "Affichage de l'élément _START_ à _END_ sur _TOTAL_ éléments", sInfoEmpty: "Affichage de l'élément 0 à 0 sur 0 élément", sInfoFiltered: "(filtré à partir de _MAX_ éléments au total)", sInfoPostFix: "", sInfoThousands: ",", sLengthMenu: "Afficher _MENU_ éléments", sLoadingRecords: "Chargement...", sProcessing: "Traitement...", sSearch: "Rechercher :", sZeroRecords: "Aucun élément correspondant trouvé", oPaginate: { sFirst: "Premier", sLast: "Dernier", sNext: "Suivant", sPrevious: "Précédent", }, oAria: { sSortAscending: ": activer pour trier la colonne par ordre croissant", sSortDescending: ": activer pour trier la colonne par ordre décroissant", }, }, buttons: [ { extend: "copyHtml5", exportOptions: { columns: [0, ":visible"], }, }, { extend: "pdfHtml5", exportOptions: { columns: ":visible", }, }, { extend: "print", exportOptions: { columns: ":visible", }, }, { extend: "csv", exportOptions: { columns: ":visible", }, }, ], }); $(document).on("click", "#refresh", function (e) { table_companies.api().ajax.reload(function () { hide_loading_message(); show_message("Rafraîchissement terminé", "success"); }, true); }); // add new sidebar starts // $(document).on("click", "#add_tech", function (e) { e.preventDefault(); $("#titre_h4").text("Affecter un nouveau rédacteur"); $("#form_company #btn_ok").text("Affecter"); $("#form_company").attr("class", "form add"); $("#form_company").attr("data-id", ""); $("#form_company .field_container label.error").hide(); $("#form_company .field_container").removeClass("valid").removeClass("error"); $("#form_company #user_id").val(""); $("#form_company #menu_socle_id").val(""); $("#form_company #planning_prod_technicien_date_debut").val(""); $("#form_company #planning_prod_technicien_date_fin").val(""); $("#form_company #planning_prod_technicien_estimation_charge").val(""); $(".add-new-data").addClass("show"); $(".overlay-bg").addClass("show"); }); // add new sidebar ends // // hide new sidebar starts // $(".hide-data-sidebar, .cancel-data-btn, .overlay-bg").on("click", function () { $(".add-new-data").removeClass("show"); $(".overlay-bg").removeClass("show"); $("#data-name, #data-price").val(""); $("#data-category, #data-status").prop("selectedIndex", 0); }); // hide new sidebar ends // $(document).on("submit", "#form_company_tech1.add", function (e) { e.preventDefault(); var form_data = $("#form_company_tech1").serialize(); var request = $.ajax({ url: "module/planning/table/php/data_liste_planning.php?job=add_tech", cache: false, data: form_data, dataType: "json", contentType: "application/json; charset=utf-8", type: "get", }); request.done(function (output) { if (output.result == "success") { $(".modal-body #charge").val("5666"); } else { Swal.fire({ title: "ERREUR !", text: "ALERTE : " + output.message, type: "error", confirmButtonClass: "btn btn-primary", buttonsStyling: false, }); } }); request.fail(function (jqXHR, textStatus) { Swal.fire({ title: "ERREUR !", text: "ALERTE : " + output.message, type: "error", confirmButtonClass: "btn btn-primary", buttonsStyling: false, }); }); }); $(document).on("submit", "#form_company_tech2.add", function (e) { e.preventDefault(); var form_data = $("#form_company_tech2").serialize(); var request = $.ajax({ url: "module/planning/table/php/data_liste_planning.php?job=add_tech", cache: false, data: form_data, dataType: "json", contentType: "application/json; charset=utf-8", type: "get", }); request.done(function (output) { if (output.result == "success") { } else { show_message("ALERTE : " + output.message, "error"); } }); request.fail(function (jqXHR, textStatus) { show_message("ALERTE :" + output.message, "error"); }); }); $(document).on("submit", "#form_company_tech3.add", function (e) { e.preventDefault(); var form_data = $("#form_company_tech3").serialize(); var request = $.ajax({ url: "module/planning/table/php/data_liste_planning.php?job=add_tech", cache: false, data: form_data, dataType: "json", contentType: "application/json; charset=utf-8", type: "get", }); request.done(function (output) { if (output.result == "success") { } else { show_message("ALERTE : " + output.message, "error"); } }); request.fail(function (jqXHR, textStatus) { show_message("ALERTE :" + output.message, "error"); }); }); $(document).on("click", "#function_duree_traitement", function (e) { var id = $(this).data("id"); var request = $.ajax({ url: "module/planning/table/php/data_liste_planning.php?job=get_modal_plan_data", cache: false, data: "id=" + id, dataType: "json", contentType: "application/json; charset=utf-8", type: "get", }); request.done(function (output) { if (output.result == "success") { $(".modal-header h5").text("Détails affectation"); $(".modal-body #estimation_moyenne_jrs").text(output.data[0].estimation_moyenne_jrs); $(".modal-body #estimation_charge").text(output.data[0].estimation_charge); $(".modal-body #date_debut").text(output.data[0].date_debut); $(".modal-body #date_fin").text(output.data[0].date_fin); $(".modal-body #nbre_de_jours_reels").text(output.data[0].nbre_de_jours_reels); $(".modal-body #remarques").text(output.data[0].remarques); $(".modal-body #prestation_md").text(output.data[0].prestation_md); $(".modal-body #prestation_pe").text(output.data[0].prestation_pe); $(".modal-body #var_ident").text(output.data[0].var_ident); $(".modal-body #var_se").text(output.data[0].var_se); $("#form_company_tech1 #planning_id").val(output.data[0].planning_prod_id); $("#form_company_tech2 #planning_id").val(output.data[0].planning_prod_id); $("#form_company_tech3 #planning_id").val(output.data[0].planning_prod_id); } else { show_message("Une erreur lors de l'enregistrement", "error"); } }); request.fail(function (jqXHR, textStatus) { show_message("Une erreur lors de l'enregistrement " + textStatus, "error"); }); }); $(document).on("click", "#function_edit_chapitre", function (e) { e.preventDefault(); var id = $(this).data("id"); var name = $(this).data("name"); var request = $.ajax({ url: "module/planning/table/php/data_liste_chapitre.php?job=get_chapitre_edit", cache: false, data: "id=" + id, dataType: "json", contentType: "application/json; charset=utf-8", type: "get", }); request.done(function (output) { if (output.result == "success") { $("#titre_h4").text("Modifier le niveau : " + name); $("#form_company #btn_ok").text("Modifier"); $("#form_company").attr("class", "form edit"); $("#form_company").attr("data-id", id); $("#form_company #nom_chapitre").val(output.data[0].nom_chapitre); $(".add-new-data").addClass("show"); $(".overlay-bg").addClass("show"); } else { hide_loading_message(); show_message("Une erreur s'est produite lors de l'enregistrement", "error"); } }); }); $(document).on("submit", "#form_company.edit", function (e) { e.preventDefault(); if (form_company.valid() == true) { var id = $("#form_company").attr("data-id"); var form_data = $("#form_company").serialize(); var request = $.ajax({ url: "module/chapitre/table/php/data_liste_chapitre.php?job=chapitre_edit&id=" + id, cache: true, data: form_data, dataType: "json", contentType: "application/json; charset=utf-8", type: "get", }); request.done(function (output) { if (output.result == "success") { $(".add-new-data").removeClass("show"); $(".overlay-bg").removeClass("show"); table_companies.api().ajax.reload(function () { Swal.fire({ title: "BRAVO !", text: "Chapitre modifié avec succés", type: "success", confirmButtonClass: "btn btn-primary", buttonsStyling: false, }); //toastr.success('Nouvelle équipe ajoutée avec succés', 'succés', { positionClass: 'toast-bottom-full-width' , "progressBar": true , "closeButton": true }); }, true); } else { Swal.fire({ title: "Annulée", text: "La demande de modification a échoué : " + textStatus, type: "error", confirmButtonClass: "btn btn-success", }); } }); request.fail(function (jqXHR, textStatus) { Swal.fire({ title: "Annulée", text: "La demande de modification a échoué : " + textStatus, type: "error", confirmButtonClass: "btn btn-success", }); }); } }); }); })(jQuery);
import React from 'react'; export default React.createClass({ displayName: "TabLinks", propTypes: { currentView: React.PropTypes.string.isRequired, linkList: React.PropTypes.array.isRequired, onChangeView: React.PropTypes.func.isRequired }, onChangeView: function(item) { this.props.onChangeView(item); }, renderLinks: function(item, i) { let active = ""; if (item === this.props.currentView) { active = "TabLinks--active"; } return ( <li key={i} className="TabLinks-link"> <a className={active} onClick={this.onChangeView.bind(this, item)} > {item} </a> </li> ) }, render: function() { return ( <ul className="TabLinks clearFix"> {this.props.linkList.map(this.renderLinks)} </ul> ) } });
import React from 'react'; const Btn = (props) => { const { title, type, handleClick, } = props; const styles = { grey: { backgroundColor: '#DDE3E9', color: '#585D61', }, aqua: { backgroundColor: '#7AD9E0', color: '#fff', }, crimson: { backgroundColor: '#E8596C', color: '#fff', }, }; return ( <div className='btn' style={styles[type]} onClick={handleClick} > {title} </div> ) }; export default Btn;
require('styles/MemberList.scss'); require('styles/App.scss'); import React from 'react'; import InputComponent from './Input.js' import MemberItemComponent from './MemberItem.js' let yiyiImage = require('../images/WechatIMG11.jpg'); class MemberListComponent extends React.Component { constructor(props) { super(props); this.state = { bannerUrl: yiyiImage, totleMembers: 39, totleHot: 4000000, finishTime: 1500537523, members: ['校园赛区第七场资格赛网络人气12345678', '校园赛区第七场资格赛网络人气12345678', '校园赛区第八场资格赛网络人气12345678', '校园赛区第七场资格赛网络人气12345678', '校园赛区第八场资格赛网络人气12345678', '校园赛区第七场资格赛网络人气12345678', '校园赛区第八场资格赛网络人气12345678'] } } converTime() { var curTime = Date.parse(new Date()) / 1000; var deltaTime = this.state.finishTime - curTime; var second = deltaTime % 60; var min = parseInt(deltaTime / 60) % 60; var hour = parseInt(deltaTime / 3600) % 24; var day = parseInt(deltaTime / 86400) return day + '天' + hour + '时' + min + '分' + second + '秒'; } render() { return ( <div className="member-list-component"> <div className="banner"> <img src={this.state.bannerUrl}/> </div> <div className="topinfo-layout"> <div className="layout1"> <div className="input"> <InputComponent placeHolder="搜索学员"/> </div> <div className="button margin-left-5">赛事直播</div> </div> <div className="layout2"> <div className="info-layout"> <div> <div className="info-txt margin-right-5"> 选手:{this.state.totleMembers} </div> <div className="info-txt"> 综合人气指数:{this.state.totleHot} </div> </div> <div className="info-txt margin-top-5"> 距离投票结束:{this.converTime()} </div> </div> <div className="button margin-left-5">活动说明</div> </div> </div> <div className="member-list"> {this.state.members.map((it, index)=>{ return ( <MemberItemComponent key={index} index={index+1} name="名称" hot="12355"/> ); })} </div> </div> ); } } MemberListComponent.defaultProps = { }; export default MemberListComponent;
// 推荐页面接口 // 获取签名方法 const getSecuritySign = require('../sign') // 请求相关函数 const { get } = require('../request') // utils const { getRandomVal } = require('../utils') // 响应成功code const CODE_OK = 0 // 注册推荐列表接口路由 function registerRecommend (app) { app.get('/api/getRecommend', (req, res) => { // 第三方服务接口 url const url = 'https://u.y.qq.com/cgi-bin/musics.fcg' // 构造请求 data 参数 const data = JSON.stringify({ comm: { ct: 24 }, recomPlaylist: { method: 'get_hot_recommend', param: { async: 1, cmd: 2 }, module: 'playlist.HotRecommendServer' }, focus: { module: 'music.musicHall.MusicHallPlatform', method: 'GetFocus', param: {} } }) // 随机数值 const randomVal = getRandomVal('recom') // 计算签名值 const sign = getSecuritySign(data) // 发送 get 请求 get(url, { sign, '-': randomVal, data }).then(response => { const data = response.data if (data.code === CODE_OK) { // 处理轮播图数据 const focusList = data.focus.data.shelf.v_niche[0].v_card const sliders = [] const jumpPrefixMap = { 10002: 'https://y.qq.com/n/yqq/album/', 10014: 'https://y.qq.com/n/yqq/playlist/', 10012: 'https://y.qq.com/n/yqq/mv/v/' } // 最多获取 10 条数据 const len = Math.min(focusList.length, 10) for (let i = 0; i < len; i++) { const item = focusList[i] const sliderItem = {} // 单个轮播图数据包括 id、pic、link 等字段 sliderItem.id = item.id sliderItem.pic = item.cover if (jumpPrefixMap[item.jumptype]) { sliderItem.link = jumpPrefixMap[item.jumptype] + (item.subid || item.id) + '.html' } else if (item.jumptype === 3001) { sliderItem.link = item.id } sliders.push(sliderItem) } // 处理推荐歌单数据 const albumList = data.recomPlaylist.data.v_hot const albums = [] for (let i = 0; i < albumList.length; i++) { const item = albumList[i] const albumItem = {} // 推荐歌单数据包括 id、username、title、pic 等字段 albumItem.id = item.content_id albumItem.username = item.username albumItem.title = item.title albumItem.pic = item.cover albums.push(albumItem) } // 往前端发送一个标准格式的响应数据,包括成功错误码和数据 res.json({ code: CODE_OK, result: { sliders, albums } }) } else { res.json(data) } }) }) } module.exports = registerRecommend
const mongoose = require ('mongoose') const Schema = mongoose.Schema //creat schema set it to new schema object which takes object const ItemSchema = new Schema ({ name:{ type:String , required:true } , date:{ type:Date, default:Date.now } }) //the whole model is exported now and to bring another file module.exports=item = mongoose.model('item',ItemSchema)
jQuery.noConflict(); var comments = []; var options = []; var all_comments = []; var sort_key = ""; var url = kintone.api.url('/k/v1/records', true); var domain = url.substr( 0,url.indexOf("/k/")); var record_url =""; // Vueのインスタンスを作成 var vm = new Vue({ data: { comments: comments } }); (function ($, PLUGIN_ID) { 'use strict'; kintone.events.on('mobile.app.record.index.show', async function (event) { var customize_id = await get_customize_id(); if (String(event.viewId) !== customize_id) { return event; } var app_ids = await get_app_ids(); for (var i = 0; i < app_ids.length; i++) { options.push( { name: app_ids[i]['name'], id: app_ids[i]['appId'] } ) // Vueインスタンスをカスタマイズビューで用意した#appにマウントしデータをセット vm.$mount('#app'); Vue.set(vm, 'options', options); } return event; }); async function get_customize_id() { var config = await kintone.plugin.app.getConfig(PLUGIN_ID); return config['customize_id'] } async function get_app_ids() { var resp = await kintone.api(kintone.api.url('/k/v1/apps', true), 'GET', {}); return resp['apps'] } })(jQuery, kintone.$PLUGIN_ID); function view_comments(sel_app) { var app_id = document.getElementById(sel_app).value; extract_comments(app_id) } async function extract_comments(app_id) { sort_key = "date"; var total_count = await get_current_record_no(app_id); console.log('最新レコードNo:' + total_count); for (let record_id = total_count; record_id !== 0; record_id--) { var record = await get_record(app_id, record_id); if (record !== null) { all_comments = record['comments']; for (var i = 0; i < all_comments.length; i++) { record_url = domain + "/k/" + app_id + "/show#record=" + record_id comments.push( { record: record_url, date: all_comments[i]['createdAt'], user: all_comments[i]['creator']['name'], comment: all_comments[i]['text'] } ) comments.sort(compare); // 作成されたVueインスタンスをカスタマイズビューで用意した #app にマウント vm.$mount('#app'); // データをセット Vue.set(vm, 'comments', comments); } } } } // 最新レコードNoを取得 async function get_current_record_no(app_id) { var resp = await kintone.api(kintone.api.url('/k/v1/records', true), 'GET', { "app": app_id, "id": 100, "totalCount": true }); var current_record_no = resp['records'][0]['$id']['value']; return current_record_no } // レコードを取得 async function get_record(app_id, record_id) { console.log('レコード取得:' + record_id); try { var resp = await kintone.api(kintone.api.url('/k/v1/record/comments', true), 'GET', { "app": app_id, "record": record_id }); return resp } catch (err) { return null } } function sortBy(columns){ console.log("sortBy:"+columns) sort_key = columns; comments.sort(compare); } function compare( a, b ){ var r = 0; if( a[sort_key] > b[sort_key] ){ r = -1; } else if( a[sort_key] < b[sort_key] ){ r = 1; } return r; }
var routeUtils = require('./route_utils.js'); var logger = require(LIB_DIR + 'log_factory').create("reports_data_route"); var reportsDataImpl = require(IMPLS_DIR + 'reports_data_impl'); var ReportsDataRoute = function(app){ app.get('/reports_data/:id', function(req, res){ routeUtils.getById(req, res, reportsDataImpl); }); app.get('/reports_data', function(req, res){ var userId = req.user.id; reportsDataImpl.getReportsDataForUser(userId, function(err, data){ if(err == undefined){ routeUtils.respond(req, res, data); }else{ routeUtils.respond(req, res, err); } }); }); }; module.exports = function(app){ return new ReportsDataRoute(app); };
import main from 'main' import map from 'ramda/src/map' import propEq from 'ramda/src/propEq' import filter from 'ramda/src/filter' import always from 'main/signals/processes/always' import pipe from 'main/signals/pipe' import preventDefault from 'main/processes/preventDefault' import valueOnEnter from 'main/processes/valueOnEnter' import css from './styles.css' const presenter = (model) => map((col) => ({ ...col, over: col.id === model.over, tasks: map((task) => ({ ...task, dragging: model.dragging === task.id }), filter(propEq('col', col.id), model.tasks)) }), model.cols) const view = (cols) => ( ['main', [ addCol, ['h1', 'Act Kanban Board'], ['table', { class: css.grid }, [ ['tr', map(col, cols)] ]] ]] ) const col = (col) => { return ( ['td', { class: css.col, style: { border: col.over ? '1px solid #4592fb' : '1px solid #eee' }, drop: { drop: col.id }, dragenter: { over: pipe(preventDefault, always(col.id)) }, dragover: (ev) => ev.preventDefault() }, [ ['h3', [col.title, ' (', col.tasks.length, ')']], col.id === 1 && addTask, ...map(task, col.tasks) ] ] ) } const addTask = () => ['input', { class: css.addTask, placeholder: 'Add task', value: '', keyup: { addTask: valueOnEnter } }] const addCol = () => ['input', { class: css.addCol, placeholder: 'Add column', value: '', keyup: { addCol: valueOnEnter } }] const task = (task) => ['div', { draggable: true, class: css.task, style: { opacity: task.dragged ? 0.3 : 1 }, dragstart: { drag: task.id }, dragend: { drag: null } }, task.desc] const reducer = (state, { type, payload }) => { const uid = state.uid + 1 switch (type) { case 'addCol': return { ...state, uid, cols: [ ...state.cols, { id: uid, title: payload } ] } case 'addTask': return { ...state, uid, tasks: [ { id: uid, desc: payload, col: 1 }, ...state.tasks ] } case 'drag': return { ...state, dragging: payload, over: null } case 'drop': return { ...state, dragging: null, over: null, tasks: map((task) => ( task.id === state.dragging ? { ...task, col: payload } : task ), state.tasks) } case 'over': return { ...state, over: payload } default: return state } } const model = { uid: 3, dragging: null, over: null, cols: [ { id: 1, title: 'todo' }, { id: 2, title: 'doing' }, { id: 3, title: 'done' } ], tasks: [ { id: 1, desc: 'Add drag & drop example', col: 3 }, { id: 2, desc: 'Implement presenters', col: 1 }, { id: 3, desc: 'Finish docs', col: 1 } ] } main(pipe(presenter, view), { model, reducer })
import React from 'react' import {NoBannerLayout} from 'layouts' import StatusTimeline from 'status/statusTimeline/statusTimeline.js'; export default class Details extends React.Component { constructor(props) { super(props); this.state = { items:{} } this.backendURL = window.backendURL; this.interval = null; this._isMounted = false; } componentDidMount() { this._isMounted = true; this.getData(); this.interval = setInterval(() => this.getData() , 5000); } componentWillUnmount() { this._isMounted = false; clearInterval(this.interval); } async getData() { const { id } = this.props.match.params try { let [workpieces] = await Promise.all([ fetch(`${this.backendURL}/workpiece/${id}`).then(response => response.json()) ]); if (this._isMounted) { this.setState({ items: workpieces }); } } catch(err) { console.warn(err); }; } render() { var main = "" if (this.state.items.hasOwnProperty('_id')){ var place = "" if (this.state.items.state.place.faculty === null && this.state.items.state.place.floor === null && this.state.items.state.place.room === null){ place = "Wird transportiert" }else{ place = this.state.items.state.place.faculty + ", " + this.state.items.state.place.floor + ", " + this.state.items.state.place.room } var workpieceTable = ( <div> <p className="mb-2 font-weight-bold">Informationen zum Werkstück</p> <table className="table text-left"> <thead> <tr> <th scope="col">Feld</th> <th scope="col">Wert</th> </tr> </thead> <tbody> <tr> <td>Werkstück ID</td> <td>{this.state.items.workpieceId}</td> </tr> <tr> <td>Ort</td> <td>{place}</td> </tr> <tr> <td>Nachricht</td> <td>{this.state.items.state.message}</td> </tr> <tr className="invisible"> <td>Damit beide Reihen</td> <td>immer übereinstimmten test test tes tes tes tes</td> </tr> </tbody> </table> </div> ) var orderTable = "" if(this.state.items.hasOwnProperty('order')){ var kunde = this.state.items.order.customer.name + " " + this.state.items.order.customer.firstname var ort = this.state.items.order.customer.ort + ", " + this.state.items.order.customer.address orderTable = ( <div> <p className="mb-2 font-weight-bold">Informationen zur Bestellung</p> <div className="table-responsive"> <table className="table text-left"> <thead> <tr> <th scope="col">Feld</th> <th scope="col">Wert</th> </tr> </thead> <tbody> <tr> <td>Kunde</td> <td>{kunde}</td> </tr> <tr> <td>Ort</td> <td>{ort}</td> </tr> <tr> <td>Email</td> <td>{this.state.items.order.customer.email}</td> </tr> <tr> <td>Nummer</td> <td>{this.state.items.order.number}</td> </tr> <tr className="invisible"> <td>Damit beide Reihen</td> <td>immer übereinstimmten test test tes tes tes tes</td> </tr> </tbody> </table> </div> </div> ) } main = ( <NoBannerLayout title={"Details - " + this.state.items.workpieceId}> <div className="col-12 mt-3 mb-5 text-center"> {workpieceTable} {orderTable} <StatusTimeline className="mt-5" items={this.state.items}/> </div> </NoBannerLayout> ) } else { main = ( <NoBannerLayout title={"Werkstück nicht gefunden"}> <div className="col-md-12"> <div className="row d-flex align-self-center justify-content-center"> <div className="alert alert-danger" role="alert"> Es wurde kein Werkstück mit diesem Namen gefunden! </div> </div> </div> </NoBannerLayout> ) } return main; } }
import firebase from 'firebase/app'; import 'firebase/storage'; var firebaseConfig = { apiKey: "AIzaSyCM8wYDwxTJ3zS8h2en_GcXZmgX7SVtJUs", authDomain: "react-my-burger-c85e1.firebaseapp.com", databaseURL: "https://react-my-burger-c85e1.firebaseio.com", projectId: "react-my-burger-c85e1", storageBucket: "react-my-burger-c85e1.appspot.com", messagingSenderId: "536530677844", appId: "1:536530677844:web:93762ac256b01ea10dfdc1", measurementId: "G-SYHJJZVTYL" }; firebase.initializeApp(firebaseConfig); const storage = firebase.storage(); export { storage, firebase as default }
//07.Write a script that finds the index of given element in a sorted array of integers by using the binary search algorithm. 'use strict'; var numbers = [1, 3, 4, 6, 8, 9, 11], keyToBeFound = 4, minIndex = 0, middleIndex = 0, maxIndex = numbers.length - 1, indexFound = -1; numbers.sort(function(a,b){ return a - b; }); while (maxIndex >= minIndex) { middleIndex = minIndex + ((maxIndex - minIndex) / 2); if(numbers[middleIndex] === keyToBeFound) { indexFound = middleIndex; break; } else if (numbers[middleIndex] < keyToBeFound) minIndex = middleIndex + 1; else maxIndex = middleIndex - 1; } console.log(indexFound);
var SyntheticClipboardEvent = require("../events/synthetic_clipboard_event"), SyntheticDragEvent = require("../events/synthetic_drag_event"), SyntheticFocusEvent = require("../events/synthetic_focus_event"), SyntheticInputEvent = require("../events/synthetic_input_event"), SyntheticKeyboardEvent = require("../events/synthetic_keyboard_event"), SyntheticMouseEvent = require("../events/synthetic_mouse_event"), SyntheticTouchEvent = require("../events/synthetic_touch_event"), SyntheticUIEvent = require("../events/synthetic_ui_event"), SyntheticWheelEvent = require("../events/synthetic_wheel_event"); module.exports = { // Clipboard Events copy: SyntheticClipboardEvent, cut: SyntheticClipboardEvent, paste: SyntheticClipboardEvent, // Keyboard Events keydown: SyntheticKeyboardEvent, keyup: SyntheticKeyboardEvent, keypress: SyntheticKeyboardEvent, // Focus Events focus: SyntheticFocusEvent, blur: SyntheticFocusEvent, // Form Events change: SyntheticInputEvent, input: SyntheticInputEvent, submit: SyntheticInputEvent, // Mouse Events click: SyntheticMouseEvent, doubleclick: SyntheticMouseEvent, mousedown: SyntheticMouseEvent, mouseenter: SyntheticMouseEvent, mouseleave: SyntheticMouseEvent, mousemove: SyntheticMouseEvent, mouseout: SyntheticMouseEvent, mouseover: SyntheticMouseEvent, mouseup: SyntheticMouseEvent, // Drag Events drag: SyntheticDragEvent, dragend: SyntheticDragEvent, dragenter: SyntheticDragEvent, dragexit: SyntheticDragEvent, dragleave: SyntheticDragEvent, dragover: SyntheticDragEvent, dragstart: SyntheticDragEvent, dragdrop: SyntheticDragEvent, // Touch Events touchcancel: SyntheticTouchEvent, touchend: SyntheticTouchEvent, touchmove: SyntheticTouchEvent, touchstart: SyntheticTouchEvent, // Scroll Event scroll: SyntheticUIEvent, // Wheel Event wheel: SyntheticWheelEvent };
import React from 'react' import ReactDOM from 'react-dom' import styles from './dogs.scss'; import DogList from './DogList'; ReactDOM.render( ( <div> <h1> Who is in the doghouse? </h1> <DogList /> </div> ), document.getElementById('dog-app-root') );
//Adds Active class to the nav link of current page $(function(){ $('.nav-link').each(function(){ if ($(this).prop('href') == window.location.href) { $(this).addClass('active'); // $(this).parents('li').addClass('active'); } }); }); //Auto Hide Alert Box $(document).ready (function(){ $('.alert-dismissible').delay(3000).fadeOut(); }); //Gallery Function // MDB Lightbox Init $(function () { $("#mdb-lightbox-ui").load("mdb-addons/mdb-lightbox-ui.html"); });
app. controller('mainCtrl', ['$scope','Service', function($scope,Service){ $scope.user = 'Daniel'; $scope.url = 'https://jsonplaceholder.typicode.com'; Service.posts($scope.url + '/posts'). then(function(res){ console.log(res) $scope.posts = res.data; }) Service.albums($scope.url + '/albums'). then(function(res){ console.log(res) $scope.albums = res.data; }) }]);
const TwingTestEnvironmentStub = require('../../../mock/environment'); const TwingEnvironment = require('../../../../lib/twing/environment').TwingEnvironment; const TwingLoaderArray = require('../../../../lib/twing/loader/array').TwingLoaderArray; const TwingSource = require('../../../../lib/twing/source').TwingSource; const TwingCacheFilesystem = require('../../../../lib/twing/cache/filesystem').TwingCacheFilesystem; const TwingFilter = require('../../../../lib/twing/filter').TwingFilter; const TwingFunction = require('../../../../lib/twing/function').TwingFunction; const TwingTest = require('../../../../lib/twing/test').TwingTest; const TwingTokenParser = require('../../../../lib/twing/token-parser').TwingTokenParser; const TwingExtension = require('../../../../lib/twing/extension').TwingExtension; const TwingTestMockRuntimeLoader = require('../../../mock/runtime-loader'); const TwingErrorRuntime = require('../../../../lib/twing/error/runtime').TwingErrorRuntime; const TwingTestMockLoader = require('../../../mock/loader'); const TwingTestMockCache = require('../../../mock/cache'); const path = require('path'); const tap = require('tap'); const sinon = require('sinon'); const tmp = require('tmp'); let moduleAlias = require('module-alias'); moduleAlias.addAlias('twing/lib/runtime', path.resolve('lib/runtime.js')); function escapingStrategyCallback(name) { return name; } class TwingTestsEnvironmentTestTokenParser extends TwingTokenParser { parse(token) { } getTag() { return 'test'; } } class TwingTestsEnvironmentTestNodeVisitor { enterNode(node, env) { return node; } leaveNode(node, env) { return node; } getPriority() { return 0; } } class TwingTestsEnvironmentTestExtension extends TwingExtension { constructor() { super(); this.implementsTwingExtensionGlobalsInterface = true; } getTokenParsers() { return [ new TwingTestsEnvironmentTestTokenParser(), ]; } getNodeVisitors() { return [ new TwingTestsEnvironmentTestNodeVisitor(), ]; } getFilters() { return [ new TwingFilter('foo_filter') ]; } getTests() { return [ new TwingTest('foo_test'), ]; } getFunctions() { return [ new TwingFunction('foo_function'), ]; } getOperators() { return { unary: new Map([ ['foo_unary', {}] ]), binary: new Map([ ['foo_binary', {}] ]) }; } getGlobals() { return { foo_global: 'foo_global' }; } } class TwingTestsEnvironmentTestExtensionWithDeprecationInitRuntime extends TwingExtension { initRuntime(env) { } } class TwingTestsEnvironmentTestExtensionWithoutDeprecationInitRuntime extends TwingExtension { constructor() { super(); this.implementsTwingExtensionInitRuntimeInterface = true; } initRuntime(env) { } } class TwingTestsEnvironmentTestExtensionWithoutRuntime extends TwingExtension { getFunctions() { return [ new TwingFunction('from_runtime_array', ['TwingTestsEnvironmentTestRuntime', 'fromRuntime']), new TwingFunction('from_runtime_string', 'TwingTestsEnvironmentTestRuntime::fromRuntime') ]; } getName() { return 'from_runtime'; } } class TwingTestsEnvironmentTestRuntime { fromRuntime(name = 'bar') { return name; } } function getMockLoader(templateName, templateContent) { let loader = new TwingTestMockLoader(); sinon.stub(loader, 'getSourceContext').withArgs(templateName).returns(new TwingSource(templateContent, templateName)); sinon.stub(loader, 'getCacheKey').withArgs(templateName).returns(templateName); return loader; } tap.test('environment', function (test) { test.test('autoescapeOption', async function (test) { let loader = new TwingLoaderArray({ 'html': '{{ foo }} {{ foo }}', 'js': '{{ bar }} {{ bar }}', }); let twing = new TwingEnvironment(loader, { debug: true, cache: false, autoescape: escapingStrategyCallback }); test.same(await twing.render('html', {'foo': 'foo<br/ >'}), 'foo&lt;br/ &gt; foo&lt;br/ &gt;'); test.same(await twing.render('js', {'bar': 'foo<br/ >'}), 'foo\\x3Cbr\\x2F\\x20\\x3E foo\\x3Cbr\\x2F\\x20\\x3E'); test.end(); }); test.test('globals', async function (test) { let loader = new TwingTestMockLoader(); sinon.stub(loader, 'getSourceContext').returns(new TwingSource('', '')); // globals can be added after calling getGlobals let twing = new TwingEnvironment(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.addGlobal('foo', 'bar'); let globals = twing.getGlobals(); test.same(globals['foo'], 'bar'); // globals can be modified after a template has been loaded twing = new TwingEnvironment(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.loadTemplate('index'); twing.addGlobal('foo', 'bar'); globals = twing.getGlobals(); test.same(globals['foo'], 'bar'); // globals can be modified after extensions init twing = new TwingEnvironment(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); twing.addGlobal('foo', 'bar'); globals = twing.getGlobals(); test.same(globals['foo'], 'bar'); // globals can be modified after extensions and a template has been loaded let arrayLoader = new TwingLoaderArray({index: '{{foo}}'}); twing = new TwingEnvironment(arrayLoader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); twing.loadTemplate('index'); twing.addGlobal('foo', 'bar'); globals = twing.getGlobals(); test.same(globals['foo'], 'bar'); twing = new TwingEnvironment(arrayLoader); twing.getGlobals(); twing.addGlobal('foo', 'bar'); let template = twing.loadTemplate('index'); test.same(await template.render({}), 'bar'); // globals cannot be added after a template has been loaded twing = new TwingEnvironment(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.addGlobal('foo', 'bar'); twing.loadTemplate('index'); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals()['bar']); } // globals cannot be added after extensions init twing = new TwingEnvironment(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals()['bar']); } // globals cannot be added after extensions and a template has been loaded twing = new TwingEnvironment(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); twing.loadTemplate('index'); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals()['bar']); } // test adding globals after a template has been loaded without call to getGlobals twing = new TwingEnvironment(loader); twing.loadTemplate('index'); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals()['bar']); } test.end(); }); test.test('testExtensionsAreNotInitializedWhenRenderingACompiledTemplate', async function (test) { let cache = new TwingCacheFilesystem(tmp.dirSync().name); let options = {cache: cache, auto_reload: false, debug: false}; // force compilation let loader = new TwingLoaderArray({index: '{{ foo }}'}); let twing = new TwingEnvironment(loader, options); let key = cache.generateKey('index', twing.getTemplateClass('index')); cache.write(key, twing.compileSource(new TwingSource('{{ foo }}', 'index'))); // check that extensions won't be initialized when rendering a template that is already in the cache twing = new TwingTestEnvironmentStub(loader, options); twing['initExtensions'] = () => { }; sinon.stub(twing, 'initExtensions'); sinon.assert.notCalled(twing['initExtensions']); // render template let output = await twing.render('index', {foo: 'bar'}); test.same(output, 'bar'); test.end(); }); test.test('autoReloadCacheMiss', function (test) { let templateName = test.name; let templateContent = test.name; let cache = new TwingTestMockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new TwingTestEnvironmentStub(loader, {cache: cache, auto_reload: true, debug: false}); sinon.stub(cache, 'generateKey').returns('key'); sinon.stub(cache, 'getTimestamp').returns(0); sinon.stub(cache, 'write'); sinon.stub(cache, 'load'); sinon.stub(loader, 'isFresh').returns(false); twing.loadTemplate(templateName); sinon.assert.calledOnce(cache['generateKey']); sinon.assert.calledOnce(cache['getTimestamp']); sinon.assert.calledOnce(loader['isFresh']); sinon.assert.calledOnce(cache['write']); sinon.assert.calledOnce(cache['load']); test.end(); }); test.test('autoReloadCacheHit', function (test) { let templateName = test.name; let templateContent = test.name; let cache = new TwingTestMockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new TwingTestEnvironmentStub(loader, {cache: cache, auto_reload: true, debug: false}); sinon.stub(cache, 'generateKey').returns('key'); sinon.stub(cache, 'getTimestamp').returns(0); sinon.stub(cache, 'write'); sinon.stub(cache, 'load'); sinon.stub(loader, 'isFresh').returns(true); twing.loadTemplate(templateName); sinon.assert.calledOnce(cache['generateKey']); sinon.assert.calledOnce(cache['getTimestamp']); sinon.assert.calledOnce(loader['isFresh']); sinon.assert.calledOnce(cache['write']); sinon.assert.calledTwice(cache['load']); test.end(); }); test.test('autoReloadOutdatedCacheHit', function (test) { let templateName = test.name; let templateContent = test.name; let cache = new TwingTestMockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new TwingTestEnvironmentStub(loader, {cache: cache, auto_reload: true, debug: false}); let now = new Date(); sinon.stub(cache, 'generateKey').returns('key'); sinon.stub(cache, 'getTimestamp').returns(now); sinon.stub(cache, 'write'); sinon.stub(cache, 'load'); sinon.stub(loader, 'isFresh').returns(false); twing.loadTemplate(templateName); sinon.assert.calledOnce(cache['generateKey']); sinon.assert.calledOnce(cache['getTimestamp']); sinon.assert.calledOnce(loader['isFresh']); sinon.assert.calledOnce(cache['write']); sinon.assert.calledOnce(cache['load']); test.end(); }); test.test('hasGetExtensionByClassName', function (test) { let twing = new TwingEnvironment(new TwingTestMockLoader()); let ext = new TwingTestsEnvironmentTestExtension(); twing.addExtension(ext); test.true(twing.hasExtension('TwingTestsEnvironmentTestExtension')); test.same(twing.getExtension('TwingTestsEnvironmentTestExtension'), ext); test.end(); }); test.test('addExtension', function (test) { let twing = new TwingEnvironment(new TwingTestMockLoader()); let ext = new TwingTestsEnvironmentTestExtension(); twing.addExtension(ext); test.true(twing.getTags().has('test')); test.true(twing.getFilters().has('foo_filter')); test.true(twing.getFunctions().has('foo_function')); test.true(twing.getTests().has('foo_test')); test.true(twing.getUnaryOperators().has('foo_unary')); test.true(twing.getBinaryOperators().has('foo_binary')); test.true(twing.getGlobals()['foo_global']); let visitors = twing.getNodeVisitors(); let found = false; for (let visitor of visitors) { if (visitor instanceof TwingTestsEnvironmentTestNodeVisitor) { found = true; } } test.true(found); test.end(); }); test.test('addMockExtension', function (test) { let extension = sinon.mock(TwingExtension).object; let loader = new TwingLoaderArray({page: 'hey'}); let twing = new TwingEnvironment(loader); twing.addExtension(extension); test.same(twing.getExtension(extension.constructor.name).name, 'TwingExtension'); test.true(twing.isTemplateFresh('page', new Date().getTime())); test.end(); }); test.test('initRuntimeWithAnExtensionUsingInitRuntimeNoDeprecation', function (test) { let loader = new TwingLoaderArray({}); let twing = new TwingEnvironment(loader); sinon.stub(loader, 'getCacheKey').returns(''); sinon.stub(loader, 'getSourceContext').returns(new TwingSource('', '')); twing.addExtension(new TwingTestsEnvironmentTestExtensionWithoutDeprecationInitRuntime()); twing.loadTemplate(''); sinon.assert.calledOnce(loader['getSourceContext']); // add a dummy assertion here, the only thing we want to test is that the code above // can be executed without throwing any deprecations test.pass(); test.end(); }); test.test('overrideExtension', function (test) { let twing = new TwingEnvironment(new TwingLoaderArray({})); twing.addExtension(new TwingTestsEnvironmentTestExtension()); test.throws(function () { twing.addExtension(new TwingTestsEnvironmentTestExtension()); }, new Error('Unable to register extension "TwingTestsEnvironmentTestExtension" as it is already registered.')); test.end(); }); test.test('addRuntimeLoader', async function (test) { let runtimeLoader = new TwingTestMockRuntimeLoader(); sinon.stub(runtimeLoader, 'load').returns(new TwingTestsEnvironmentTestRuntime()); let loader = new TwingLoaderArray({ func_array: '{{ from_runtime_array("foo") }}', func_array_default: '{{ from_runtime_array() }}', func_array_named_args: '{{ from_runtime_array(name="foo") }}', func_string: '{{ from_runtime_string("foo") }}', func_string_default: '{{ from_runtime_string() }}', func_string_named_args: '{{ from_runtime_string(name="foo") }}' }); let twing = new TwingEnvironment(loader, {cache: false}); twing.addExtension(new TwingTestsEnvironmentTestExtensionWithoutRuntime()); twing.addRuntimeLoader(runtimeLoader); test.same(await twing.render('func_array'), 'foo'); test.same(await twing.render('func_array_default'), 'bar'); test.same(await twing.render('func_array_named_args'), 'foo'); test.same(await twing.render('func_string'), 'foo'); test.same(await twing.render('func_string_default'), 'bar'); test.same(await twing.render('func_string_named_args'), 'foo'); sinon.assert.called(runtimeLoader.load); test.end(); }); test.test('failLoadTemplate', function (test) { let template = 'testFailLoadTemplate.twig'; let twing = new TwingEnvironment(new TwingLoaderArray({'testFailLoadTemplate.twig': false})); test.throws(function () { twing.loadTemplate(template, 'abc'); }, new TwingErrorRuntime('Failed to load Twig template "testFailLoadTemplate.twig", index "abc": cache is corrupted.', -1, new TwingSource(false, 'testFailLoadTemplate.twig'))); test.end(); }); test.test('failLoadTemplateOnCircularReference', function (test) { let twing = new TwingEnvironment(new TwingLoaderArray({'base.html.twig': '{% extends "base.html.twig" %}'}), { cache: false }); test.throws(function () { twing.loadTemplate('base.html.twig'); }, new TwingErrorRuntime('Circular reference detected for Twig template "base.html.twig", path: base.html.twig -> base.html.twig.', 1, new TwingSource('', 'base.html.twig', ''))); test.end(); }); test.test('failLoadTemplateOnComplexCircularReference', function (test) { let twing = new TwingEnvironment(new TwingLoaderArray({ 'base1.html.twig': '{% extends "base2.html.twig" %}', 'base2.html.twig': '{% extends "base1.html.twig" %}' }), { cache: false }); test.throws(function () { twing.loadTemplate('base1.html.twig'); }, new TwingErrorRuntime('Circular reference detected for Twig template "base1.html.twig", path: base1.html.twig -> base2.html.twig -> base1.html.twig.', 1, new TwingSource('', 'base1.html.twig', ''))); test.end(); }); test.end(); });
/** * An Object containing all utility functions */ const utilityMethods = { }; module.exports = utilityMethods;
/* Create a function that takes in a number as a string n and returns the number without trailing and leading zeros. Trailing Zeros are the zeros after a decimal point which don't affect the value (e.g. the last three zeros in 3.4000 and 3.04000). Leading Zeros are the zeros before a whole number which don't affect the value (e.g. the first three zeros in 000234 and 000230). */ function removeLeadingTrailing(n) { //let num = parseInt(n,10); //let ans = "" + num; let ans = "" + parseFloat(+n); return ans; //return ("" + (+n)); }
import { useReducer } from "react"; import ReturnHome from "../returnHome"; import Dashboard from "./dashboard"; import { BoardContext, initialState, reducer } from "./state"; function Collide() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> <BoardContext.Provider value={{ state, dispatch }}> <Dashboard /> </BoardContext.Provider> <ReturnHome /> </> ); } export default Collide;
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require bootstrap //= require_tree . //= require galleria/galleria var hotspot = window.hotspot = {}; hotspot.openInfoWindows = []; function getLocation() { if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(setPosition); } } function setPosition(position){ window.latitude = position.coords.latitude; window.longitude = position.coords.longitude; window.hotspot.setCenter(window.latitude, window.longitude) } function initializeGmap() { if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(setPosition); } else { console.log("No geolocation available."); var mapOptions = { center: new google.maps.LatLng(window.latitude || 33.57343, window.longitude || -85.09874000000001), zoom: 18 }; window.hotspot.map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); } } hotspot.addMarkerToMap = function(lat, long, name, description, id){ var contentString = '<div id="content">'+ '<div id="siteNotice">'+ '</div>'+ '<h1 id="firstHeading" class="firstHeading">' + name + '</h1>'+ '<div id="bodyContent">'+ '<p>' + description + '</p>'+ '<p><a href="/' + id + '" class="btn btn-primary">Go!</a>' + '</p>'+ '</div>'+ '</div>'; var infowindow = new google.maps.InfoWindow({ content: contentString }); var image = { url: "/assets/pepper.png", size: new google.maps.Size(20, 32), origin: new google.maps.Point(0,0), anchor: new google.maps.Point(0, 32) }; var marker = new google.maps.Marker({ title: name, map: window.hotspot.map, icon: image, position: new google.maps.LatLng(lat, long) }); google.maps.event.addListener(marker, 'click', function() { hotspot.openInfoWindows.forEach(function(iw) { iw.close(); }); infowindow.open(window.hotspot.map,marker); hotspot.openInfoWindows.push(infowindow); }); } hotspot.addMarkerIconToMap = function(lat, long){ var image = { url: "/assets/pepper.png", size: new google.maps.Size(20, 32), origin: new google.maps.Point(0,0), anchor: new google.maps.Point(0, 32) }; var marker = new google.maps.Marker({ map: window.hotspot.map, icon: image, position: new google.maps.LatLng(lat, long) }); } hotspot.setCenter = function(lat, lng) { window.hotspot.map.setCenter(new google.maps.LatLng(lat, lng)); } hotspot.addMovableMarker = function(lat, long) { } hotspot.codeAddress = function(address) { var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { window.hotspot.map.setCenter(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng())); } }); } hotspot.initialize = function(lat, lng){ if (!lat && window.hotspot.useCurrentLocation) { getLocation(); } var mapOptions = { center: new google.maps.LatLng(window.latitude || 33.57343, window.longitude || -85.09874000000001), zoom: 12 }; window.hotspot.map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); google.maps.event.addDomListener(window, 'load', initializeGmap); }
import { inject as service } from '@ember/service'; import { equal } from '@ember/object/computed'; import Component from '@ember/component'; import { computed, observer } from '@ember/object'; import Ember from 'ember'; import RecognizerMixin from 'ember-gestures/mixins/recognizers'; import layout from './template'; import { run } from '@ember/runloop'; import { getOwner } from '@ember/application'; const { String } = Ember; export default Component.extend(RecognizerMixin, { window, layout, viewport: service(), recognizers: 'swipe', classNameBindings: ['isTestLike'], init() { this._super(...arguments); this.items = this.items || []; }, config: computed(function () { return getOwner(this).resolveRegistration('config:environment'); }), isTestLike: computed('config', function () { const config = this.config; return config.environment === 'test' || config.environment === 'development' && this.get('window.location.pathname') === '/tests'; }), swipeLeft() { this.goToNextItem(); }, swipeRight() { this.goToPreviousItem(); }, goToNextItem() { if (!this.isLastPage) { this.incrementProperty('currentItem', this.itemsPerPage); } }, goToPreviousItem() { if (!this.isFirstPage) { this.decrementProperty('currentItem', this.itemsPerPage); } }, classNames: [ 'asp-scroll', 'ember-appointment-slots-pickers' ], /** * Represents the index of the left most * item currently and entirely in view * @type {Number} */ currentItem: 0, width: computed('isRendered', 'viewport.width', function () { this.get('viewport.width'); return this.isRendered ? this.$().width() : 0; }), scrollAreaWidth: computed('itemWidth', 'items.length', function () { return this.itemWidth * this.get('items.length'); }), itemWidth: computed('isRendered', 'viewport.width', 'items.length', 'currentItem', function () { this.get('viewport.width');//to refresh when viewport is refreshed. A bit strange, but needed //items.length is needed, too (when going from 0 to X items) return this.isRendered ? this.$('.asp-scroll-area > :first-child').width() : 0; }), // 120 scrollAreaOffset: computed( 'currentItem', 'currentPage', 'itemWidth', 'itemsPerPage', 'isLastPage', 'isFirstPage', 'scrollAreaWidth', 'width', function () { let offset; if (this.isLastPage && !this.isFirstPage) { offset = this.scrollAreaWidth - this.width; } else { offset = this.currentItem * this.itemWidth; } return -offset; } ), scrollAreaStyle: computed('scrollAreaWidth', 'scrollAreaOffset', function () { const width = this.scrollAreaWidth; const display = !width && this.displayAfterRender ? 'none' : ''; const offset = this.scrollAreaOffset; return String.htmlSafe(` width: ${width}px; display: ${display}; -ms-transform: translate3d(${offset}px,0,0); -o-transform: translate3d(${offset}px,0,0); -moz-transform: translate3d(${offset}px,0,0); -webkit-transform: translate3d(${offset}px,0,0); transform: translate3d(${offset}px,0,0); `); }), pages: computed('items.length', 'itemsPerPage', function () { return Math.ceil(this.get('items.length') / this.itemsPerPage); }), currentPage: computed('currentItem', 'itemsPerPage', function () { return Math.floor(this.currentItem / this.itemsPerPage); }), itemsPerPage: computed('width', 'itemWidth', function () { if (!this.itemWidth) { return 1; } return Math.floor(this.width / this.itemWidth); }), isFirstPage: equal('currentPage', 0), isLastPage: computed('currentPage', 'pages', function () { return this.currentPage === this.pages - 1; }), _recomputeItemWidth() { if (!this.isDestroyed) { this.set('isRendered', true); this.notifyPropertyChange('itemWidth'); this._onIndexChange(); } }, didInsertElement() { //needed when not loading the slots sync this._super(...arguments); run.next(this, '_recomputeItemWidth'); }, didUpdateAttrs() { //needed when loading the slots async, at least when //no loader so keeping it to be on the safe side this._super(...arguments); run.next(this, '_recomputeItemWidth'); }, //case where appointment.appointmentSlot resolves later (appointment.appointmentSlot.content is initially null) _onIndexChange: observer('index', function () {//eslint-disable-line const index = this.index; if (!this.isDestroyed && index !== undefined) { this.set( 'currentItem', Math.floor(index / this.itemsPerPage) * this.itemsPerPage ); } }), actions: { /** * Slide to the next set of items * @return {undefined} */ next() { this.goToNextItem(); }, /** * Slide to the previous set of items * @return {undefined} */ prev() { this.goToPreviousItem(); } }, });
const sdk = require('@defillama/sdk') const { getBlock } = require('../helper/getBlock') const {sumTokensSharedOwners} = require('../helper/unwrapLPs') const treasury = '0xd4a7febd52efda82d6f8ace24908ae0aa5b4f956' const dai = '0x80a16016cc4a2e6a2caca8a4a498b1699ff0f844' const frax = '0x1a93b23281cc1cde4c4741353f3064709a16197d' async function tvl(timestamp, ethBlock, chainBlocks){ const block = await getBlock(timestamp, "moonriver", chainBlocks, true) const balances = {} await sumTokensSharedOwners(balances, [dai, frax], [treasury], block, "moonriver") return balances } module.exports = { moonriver:{ tvl } }
'use strict'; window.addEventListener('load', () => { showBag(); showTotalSum(); }); //let bag from common.js (Global) let allOrder = document.getElementById('allOrder'); let emptyBag = document.getElementById('emptyBag'); let checkout = document.getElementById('checkout'); let isPurchased = false; let orderSum = document.getElementById('orderSum'); let discounts = {}; // discounts Object of Arrays /*Render goods on page*/ function showBag() { let html = ''; if(isPurchased && !bag.length) { html = ` <p class="bag-empty"> Thank you for your purchase </p>`; } else if(!bag.length) { //Bag is empty html = ` <p class="bag-empty"> Your shopping bag is empty. <a href="./catalog.html"> Use Catalog to add new items</a> </p>`; } else { //Rendering page for(let i = 0; i < bag.length; i++) { let item = {}; for(let k = 0; k < window.catalog.length; k++) { if(window.catalog[k].id === bag[i].id) { item = window.catalog[k]; } } let neww = item.hasNew ? 'new' : ''; let price = item.discountedPrice || item.price; html += ` <div class="one-order-item"> <div class="one-order-thumb ${neww}"> <a href="./item.html" data-id="${item.id}"> <img src="${item.thumbnail}" alt="${item.title}"> </a> </div> <div class="one-order-right"> <div class="one-order-info"> <h6 class="one-order-info__title">${item.title}</h6> <span class="one-order-info__price">&pound;${price}</span> </div> <div class="one-order-control"> <p class="one-order-control__color"> Color: <span>${item.colors[bag[i].color]}</span> </p> <p class="one-order-control__size"> Size: <span>${item.sizes[bag[i].size]}</span> </p> <div class="one-order-control__qty"> Quantity: <span class="minus" data-index="${i}">_</span> <input class="input-qty" type="text" value="${bag[i].count}" maxlength="3" > <span class="plus" data-index="${i}">+</span> </div> </div> <div class="remove-item" data-index="${i}"> <span>Remove item</span> </div> </div> </div> `; } } allOrder.innerHTML = html; let pluses = document.getElementsByClassName('plus'); for(let i = 0; i < pluses.length; i++) { pluses[i].onclick = function() { plusGoods.call(this); } } let minuses = document.getElementsByClassName('minus'); for (var i = 0; i < minuses.length; i++) { minuses[i].onclick = minusGoods; } let removes = document.getElementsByClassName('remove-item'); for (let i = 0; i < removes.length; i++) { removes[i].onclick = removeGoods; } } //Show bottom total sum function showTotalSum() { let count = 0; let totalPrice = 0; bag.forEach( (obj) => { count += obj.count; window.catalog.forEach( (el) => { if(el.id === obj.id) { let price = el.discountedPrice || el.price; totalPrice += parseFloat(price) * obj.count; totalPrice = +totalPrice.toFixed(2); } }); }); let dis = ` <div class="order-sum__discount"> Applied discount: <span>${currency} ${window.bestOffer.discount.toFixed(2)}</span> </div>`; let isDis = hasDiscount() ? dis : ''; let curr = count > 0 ? currency : ''; let html = ` ${isDis} <p>Total price: <strong>${curr} ${totalPrice}</strong></p>`; orderSum.innerHTML = html; } //Increase the quantity of goods function plusGoods() { let index = this.dataset.index; plusDiscount(bag[index].id); bag[index].count++; showBag(); saveBagToLS(); showMiniBag(); showTotalSum(); } //Decrease the quantity of goods function minusGoods() { let index = this.dataset.index; removeDiscount(bag[index].id); if(bag[index].count > 1) { bag[index].count--; } else { bag.splice(index,1); } showBag(); saveBagToLS(); showMiniBag(); showTotalSum(); } //Delete the good function removeGoods() { let index = this.dataset.index; removeDiscount(bag[index].id); bag.splice(index,1); showBag(); saveBagToLS(); showMiniBag(); showTotalSum(); } //Save bag to localStorage function saveBagToLS() { localStorage.setItem('bag', JSON.stringify(bag)); } //Empty bag emptyBag.onclick = () => removeBag(); function removeBag() { bag = []; removeDiscount(); showBag(); saveBagToLS(); showMiniBag(); showTotalSum(); } //Checkout checkout.onclick = () => clearBag(); function clearBag() { if(bag.length) { isPurchased = true; } bag = []; removeDiscount(); showBag(); saveBagToLS(); showMiniBag(); showTotalSum(); } //****************// // Check discount // //****************// //Check the discounts from the localStorage function checkDiscount() { if( localStorage.getItem('discounts') ) { discounts = JSON.parse( localStorage.getItem('discounts') ); } } function saveDiscountToLS() { localStorage.setItem('discounts', JSON.stringify(discounts)); } function hasDiscount() { checkDiscount(); if(!discounts.left || !discounts.right) return; let isDiscount = (discounts.left.length > 0) && (discounts.right.length > 0) ? true : false; return isDiscount; } function removeDiscount(id) { // if it has not id remove All if(!id) discounts = {}; window.bestOffer.left.forEach( (item) => { if(item === id && discounts.left) { let index = discounts.left.indexOf(id); if(index !== -1) { discounts.left.splice(index,1); } } }); window.bestOffer.right.forEach( (item) => { if(item === id && discounts.right) { let index = discounts.right.indexOf(id); if(index !== -1) { discounts.right.splice(index,1); } } }); saveDiscountToLS(); } function plusDiscount(id) { // if it has not id remove All if(!id) return; window.bestOffer.left.forEach( (item) => { if(item === id && discounts.left) { discounts.left.push(id); } }); window.bestOffer.right.forEach( (item) => { if(item === id && discounts.right) { discounts.right.push(id); } }); saveDiscountToLS(); }
var fullName = $('h1.user-name').first().text(); var userName = fullName.replace(/\)$/, '').match(/[\w\d\-_]*$/)[0]; var userData; //var request = kango.xhr.getXMLHttpRequest(); var requestDetails = { method: 'GET', url: 'http://photoapps.ru/mywed/user/profile/' + userName + '.json', async: true, contentType: 'json' }; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(data) { if (xhr.readyState == 4) { if (xhr.status == 200 && xhr.responseText != null) { var userData = JSON.parse(xhr.responseText); //userData = data.response; prependHTML = "<tr><td class='field-name'>Позиция:</td><td>" + userData.position + ", <a href='http://www.mywed.ru/photographer/popular/page/" + userData.current_page +"/'>" + userData.current_page +" страница</a></td></tr>"; prependHTML += "<tr><td class='field-name'>По городу:</td><td>" + userData.position_by_city +", " + userData.page_by_city +" страница</td></tr>"; prependHTML += "<tr><td colspan='2'><a href='http://photoapps.ru/mywed/user/profile/" + userName + "'>Расширенная статистика</a></td></tr>"; prependHTML += "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>"; $('table.photographer-info').first().prepend(prependHTML); } else { console.log("Can't get user data from photoapps.ru"); } } } // Note that any URL fetched here must be matched by a permission in // the manifest.json file! var url = 'http://photoapps.ru/mywed/user/profile/' + userName + '.json'; xhr.open('GET', url, true); xhr.send();
import { useState } from 'react'; import { Container, Control, Label, Indicator, Options, Option, } from './styles'; export default function Select({ label = 'Select', options = [], value, setValue, children, ...props }) { const [showOptions, setShowOptions] = useState(false); function toggleShow() { setShowOptions(!showOptions); } return ( <Container role='listbox' value={value} onClick={toggleShow} {...props}> <Control> <Label role='label'>{!value || value === 'all' ? label : value}</Label> <Indicator> <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'> <title>Chevron Down</title> <path fill='none' stroke='currentColor' strokeLinecap='round' strokeLinejoin='round' strokeWidth='48' d='M112 184l144 144 144-144' /> </svg> </Indicator> </Control> {showOptions && ( <Options> {options.map((option) => ( <Option key={option.value} onClick={() => setValue(option.value)} role='option' value={option.value} > {option.label} </Option> ))} </Options> )} </Container> ); }
function CreateAutoComplete(options) { //Options Expected: // elId: ID of Text Box *Required // url: URL of Autocomplete webservice *Required // dependencies: JSON of Dependent Parameters/Element IDs to be sent to webservice ~Optional // should be in format [ParameterName] = ElementId // callback: callback function to be called when a value is selected ~Optional // defaultText: Placeholder text in Text Box ~Optional if (options.defaultText !== undefined) { $("#" + options.elId).val(options.defaultText); } $("#" + options.elId).autocomplete({ minLength: 2, source: function (request, response) { if (response === undefined) { return; } var postData = { term: request.term }; if (options.dependencies !== undefined) { for (var dependency in options.dependencies) { if (options.dependencies.hasOwnProperty(dependency)) { try { eval("postData." + dependency + " = '" + $("#" + options.dependencies[dependency]).val() + "';"); } catch (e) { } } } } $.ajax({ url: options.url, data: JSON.stringify(postData), dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", dataFilter: function (data) { return data; }, success: function (data) { response($.map(data.d, function (item) { return { label: item.Text, value: item.Value } })); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, select: function (event, ui) { try { event.preventDefault(); } catch (e) { } if (ui.item == null) { return; } $(this).val(ui.item.label).select(); if (ui.item.value !== undefined && ui.item.value != null && ui.item.value != -1) { if (options.callback !== undefined) { options.callback.call(this, ui.item.value); } } }, change: function (event, ui) { try { event.preventDefault(); } catch (e) { } if (ui.item == null) { return; } $(this).val(ui.item.label); }, focus: function (event, ui) { try { event.preventDefault(); } catch (e) { } if (ui.item == null) { return; } $(this).val(ui.item.label); } }); }
let express = require("express") let app = express() app.get("/", function(req, res) { res.send("<h1>Hello</h1>") }) app.get("/contact", function(req, res){ res.send("<h3>contact@joneshshrestha.com</h3>") }) app.get("/about", function(req, res){ res.send("My name is Jonesh Shrestha. Undergraduate at Kathmandu University") }) app.get("/hobby", function(req, res) { res.send("Coffee Code & Beer") }) app.listen(3000, function(){ console.log("Server started at port 3000") })
import { FILE_STATE } from "../core/config/file-states.js"; const createPromptHTMLString = (promptData) => `<div class="prompt-container"> <p class="path">${promptData.path}</p> ${ promptData.branchName ? `<p class="branch">(${promptData.branchName})</p>` : "" } <p>${promptData.symbol || "$"}</p> </div>`; const createOutputListHTMLString = (lines) => `<div class="output-list-container"> ${lines .map( (line, i) => `<p> ${line} </p>` ) .join("")} </div>`; const createHistoryLineHTMLString = (input, output, promptData) => `<div class="history-line-container"> <div class="prompt-and-input"> ${createPromptHTMLString(promptData)} <p>${input}</p> </div> ${ output ? Array.isArray(output) ? createOutputListHTMLString(output) : `<p>${output}</p>` : "" } </div>`; const createLSOutputHTMLString = (errors, results) => `<div class="ls-output-container"> ${errors ? createOutputListHTMLString(errors) : ""} ${results.map((result, i) => `<div>${result}</div>`).join("")} </div>`; const createCommitOutputHTMLString = (files, pathAndStateValues) => { const newCount = countFiles(files, FILE_STATE.NEW); const modifiedCount = countFiles(files, FILE_STATE.MODIFIED); const deletedCount = countFiles(files, FILE_STATE.DELETED); const totalCountsLine = createCountLine( (newCount || 0) + (modifiedCount || 0) + (deletedCount || 0), "changed in total" ); const countsLine = [ [newCount, "created"], [modifiedCount, "modified"], [deletedCount, "deleted"], ] .filter((value) => value[0] !== 0) .map((value) => createCountLine(value[0], value[1])) .join(", "); const fileLines = pathAndStateValues.map( (value) => `${value.state} ${value.path}` ); return `<div class="commit-output-container"> <div> <p>${totalCountsLine}</p> <p>${countsLine}</p> </div> <div> ${fileLines .map( (line, index) => `<p> ${line} </p>` ) .join("")} </div> </div>`; }; const createCountLine = (count, message) => `${count} file${count > 1 ? "s" : ""} ${message}`; const countFiles = (files, stagingState) => files .filter((file) => file.isStagingState(stagingState)) .reduce((sum, file) => sum + file.countFiles(), 0); const createStatusOutputHTMLString = ( localCurrBranch, homeDir, remoteInitialCommit, currDir ) => `<div class="status-output-container"> <div> <p>On branch ${localCurrBranch.name}</p> <p> ${createBranchUpToDateLine(localCurrBranch, remoteInitialCommit)} </p> </div> ${createStatusSectionHTMLString( "Changes to be committed:", homeDir.getStagingAreaFiles(), currDir, true )} ${createStatusSectionHTMLString( "Changes not staged for commit:", homeDir.getWorkingAreaFiles(), currDir, true, true )} ${createStatusSectionHTMLString( "Untracked files:", homeDir.getUntrackedFiles(), currDir, false, true, true )} </div>`; const createStatusSectionHTMLString = ( title, files, currDir, flatten, isWorking, hideStates ) => { const sortedPathAndStateValues = currDir.getSortedPathAndStateValues( files, flatten, isWorking ); const sortedRelativePaths = sortedPathAndStateValues.map( (value) => value.path ); const sortedStates = sortedPathAndStateValues.map((value) => value.state); return files && files.length > 0 ? `<div> <p>${title}</p> <div class="status-section-files"> ${ !hideStates ? `<div> ${sortedStates .map( (state, index) => `<p class=${isWorking ? "working-files" : "staged-files"} > ${state} </p>` ) .join("")} </div>` : "" } <div> ${sortedRelativePaths .map( (path, index) => `<p class=${isWorking ? "working-files" : "staged-files"} > ${path} </p>` ) .join("")} </div> </div> </div>` : ""; }; const createBranchUpToDateLine = (localBranch, remoteInitialCommit) => { const remoteBranch = remoteInitialCommit.findBranchByGitId(localBranch.gitId); if (!remoteBranch) { return ""; } const { ahead, behind } = localBranch.getNumCommitsDifferent(remoteBranch); if (ahead === 0 && behind === 0) { return `Your branch is up to date with 'origin/${remoteBranch.name}'.`; } if (ahead > 0 && behind === 0) { return `Your branch is ahead of 'origin/${ remoteBranch.name }' by ${ahead} commit${ahead > 1 ? "s" : ""}.`; } if (ahead === 0 && behind > 0) { return `Your branch is behind 'origin/${ remoteBranch.name }' by ${behind} commit${behind > 1 ? "s" : ""}.`; } if (ahead > 0 && behind > 0) { return `Your branch is ahead of 'origin/${ remoteBranch.name }' by ${ahead} commit${ahead > 1 ? "s" : ""} and behind 'origin/${ remoteBranch.name }' by ${behind} commit${behind > 1 ? "s" : ""}.`; } }; export { createHistoryLineHTMLString, createPromptHTMLString, createOutputListHTMLString, createLSOutputHTMLString, createCommitOutputHTMLString, createStatusOutputHTMLString, };
var config = require("config") const fetch = require("node-fetch"); const Discord = require('discord.js'); import Helpers from '../../helpers/helpers'; import format from '../../format' // all of this code could be done better, to split functions to other files // same goes to retry in the functions for server information, could be done way better module.exports = class list { constructor() { this.name = 'list'; this.alias = ['listplayers']; this.usage = `${process.env.DISCORD_COMMAND_PREFIX || config.commandPrefix}${this.name}`; this.clearMessages = []; this.maplistRaw = []; this.maplistArr = []; } async getCount(server) { return fetch(`${server}/count`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" } }) .then(response => response.json()) .then(json => { const long = json.data.players.length return long; }) .catch(error => { }) } async team1(server) { return fetch(`${server}/team_1`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" } }) .then(response => response.json()) .then(json => { let array = []; const long = json.data.players.length; for (let i = 0; i < long; i++) { const result = json.data.players[i].score; const result2 = json.data.players[i].kills; const result3 = json.data.players[i].deaths; const result4 = json.data.players[i].name; array.push(result, result2, result3, result4) } return array; }) .catch(error => { }) } async team2(server) { return fetch(`${server}/team_2`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" } }) .then(response => response.json()) .then(json => { let array = []; const long = json.data.players.length; for (let i = 0; i < long; i++) { const result = json.data.players[i].score; const result2 = json.data.players[i].kills; const result3 = json.data.players[i].deaths; const result4 = json.data.players[i].name; array.push(result, result2, result3, result4) } return array; }) .catch(error => { }) } async getMap(server) { const maps = { MP_Abandoned: 'Zavod 311', MP_Damage: 'Lancang Dam', MP_Flooded: 'Flood Zone', MP_Journey: 'Golmud Railway', MP_Naval: 'Paracel Storm', MP_Prison: 'Operation Locker', MP_Resort: 'Hainan Resort', MP_Siege: 'Siege of Shanghai', MP_TheDish: 'Rogue Transmission', MP_Tremors: 'Dawnbreaker', XP1_001: 'Silk Road', XP1_002: 'Altai Range', XP1_003: 'Guilin Peaks', XP1_004: 'Dragon Pass', XP0_Caspian: 'Caspian Border 2014', XP0_Firestorm: 'Operation Firestorm 2014', XP0_Metro: 'Operation Metro 2014', XP0_Oman: 'Gulf of Oman 2014', XP2_001: 'Lost Islands', XP2_002: 'Nansha Strike', XP2_003: 'Wavebreaker', XP2_004: 'Operation Mortar', XP3_MarketPl: 'Pearl Market', XP3_Prpganda: 'Propaganda', XP3_UrbanGdn: 'Lumpini Garden', XP3_WtrFront: 'Sunken Dragon', XP4_Arctic: 'Operation Whiteout', XP4_SubBase: 'Hammerhead', XP4_Titan: 'Hangar 21', XP4_WalkerFactory: 'Giants of Karelia', XP5_Night_01: 'Zavod: Graveyard Shift', XP6_CMP: 'Operation Outbreak', XP7_Valley: 'Dragon Valley 2015' }; return fetch(`${server}/getInfo`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" }, }) .then(response => response.json()) .then(json => { return maps[json.data[4]] }) .catch(error => { }) } async getMode(server) { const modes = { ConquestLarge0: 'Conquest Large', ConquestSmall0: 'Conquest Small', Domination0: 'Domination', Elimination0: 'Defuse', Obliteration: 'Obliteration', RushLarge0: 'Rush', SquadDeathMatch0: 'Squad Deathmatch', TeamDeathMatch0: 'Team Deathmatch', SquadObliteration0: 'Squad Obliteration', GunMaster0: 'Gun Master', }; return fetch(`${server}/getInfo`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" }, }) .then(response => response.json()) .then(json => { return modes[json.data[3]] }) .catch(error => { }) } async getIndex(server) { return fetch(`${server}/getIndices`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" } }) .then(response => response.json()) .then(json => { const index = json.data[1]; return index; }) .catch(error => { }) } async getMapArray(server) { const maps = { MP_Abandoned: 'Zavod 311', MP_Damage: 'Lancang Dam', MP_Flooded: 'Flood Zone', MP_Journey: 'Golmud Railway', MP_Naval: 'Paracel Storm', MP_Prison: 'Operation Locker', MP_Resort: 'Hainan Resort', MP_Siege: 'Siege of Shanghai', MP_TheDish: 'Rogue Transmission', MP_Tremors: 'Dawnbreaker', XP1_001: 'Silk Road', XP1_002: 'Altai Range', XP1_003: 'Guilin Peaks', XP1_004: 'Dragon Pass', XP0_Caspian: 'Caspian Border 2014', XP0_Firestorm: 'Operation Firestorm 2014', XP0_Metro: 'Operation Metro 2014', XP0_Oman: 'Gulf of Oman 2014', XP2_001: 'Lost Islands', XP2_002: 'Nansha Strike', XP2_003: 'Wavebreaker', XP2_004: 'Operation Mortar', XP3_MarketPl: 'Pearl Market', XP3_Prpganda: 'Propaganda', XP3_UrbanGdn: 'Lumpini Garden', XP3_WtrFront: 'Sunken Dragon', XP4_Arctic: 'Operation Whiteout', XP4_SubBase: 'Hammerhead', XP4_Titan: 'Hangar 21', XP4_WalkerFactory: 'Giants of Karelia', XP5_Night_01: 'Zavod: Graveyard Shift', XP6_CMP: 'Operation Outbreak', XP7_Valley: 'Dragon Valley 2015' }; let arr = [] return fetch(`${server}/listOfMaps`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" }, }) .then(response => response.json()) .then(json => { const len = json.data.length; for (let i = 2; i < len; i += 3) { arr.push(maps[json.data[i]]); } return arr; }) .catch(error => { }) } async update(server) { try { let players = await this.team1(server); if (players == 0) return 'Empty' else return format(players); } catch (err) { } } async update2(server) { try { let players = await this.team2(server); if (players == 0) return 'Empty' else return format(players); } catch (err) { } } async modeName(server) { let mode = await this.getMode(server); return mode; } async mapName(server) { let map = await this.getMap(server); return map; } async getNext(server) { try { let maps = await this.getMapArray(server) let index = await this.getIndex(server); return maps[index]; } catch (err) { } } // TODO add some reading local urls method async getGoodUrl(server) { switch (server.toString()) { case "http://server1:3000": return "" case "http://server2:3000": return "" default: return "" } } async run(bot, message, args) { if (!(message.member.roles.cache.has(process.env.DISCORD_RCON_ROLEID || config.rconRoleId) || message.member.roles.cache.has(process.env.DISCORD_RCON_ROLEID2 || config.rconRoleId2))) { message.reply("You don't have permission to use this command.") return } await message.delete() let server = await Helpers.selectServer(message) if (!server) { message.reply("Unknown error"); message.delete({ timeout: 5000 }); clearMessages(); return; } try { let embed = new Discord.MessageEmbed() .setTitle(`There are ${await this.getCount(server)}/64 players\nMap: ${await this.mapName(server)} Mode: ${await this.modeName(server)}\nNext Map: ${await this.getNext(server)}`) .setTimestamp() .setColor('GREEN') .setFooter('Author: Bartis') .setDescription(`Scores K D Names\`\`\`c\n${await this.update(server)}\n\n${await this.update2(server)}\`\`\``) message.channel.send(embed) .then(msg => { setInterval(async () => { let embedNew = new Discord.MessageEmbed() .setTitle(`There are ${await this.getCount(server)}/64 players\nMap: ${await this.mapName(server)} Mode: ${await this.modeName(server)}\nNext Map: ${await this.getNext(server)}`) .setTimestamp() .setURL(await this.getGoodUrl(server)) .setColor('GREEN') .setFooter('Author: Bartis') .setDescription(`Scores K D Names\`\`\`c\n${await this.update(server)}\n\n${await this.update2(server)}\`\`\``) msg.edit(embedNew) }, 5000) }) } catch (error) { console.log("ERROR", error) } } clearMessages() { for (const message of this.messagesToDelete) { message.delete(); } } }
var breadcrumb = angular.module('bookmarks.services', []); breadcrumb.factory('Bookmarks', function ($resource, DocumentApi, $http, $q) { var resource = $resource(API + 'database/:database'); var CLAZZ = "_studio_bookmark" resource.CLAZZ = CLAZZ; resource.changed = false; resource.getAll = function (database) { var deferred = $q.defer(); var text = API + 'command/' + database + '/sql/-/-1?format=rid,type,version,class,graph'; var query = "select * from {{clazz}} order by name"; query = S(query).template({clazz: CLAZZ}).s; $http.post(text, query).success(function (data) { deferred.resolve(data); }); return deferred.promise; } resource.init = function (database) { var deferred = $q.defer(); var text = API + 'command/' + database + '/sql/-/20?format=rid,type,version,class,graph'; var query = "CREATE CLASS {{clazz}}"; query = S(query).template({clazz: CLAZZ}).s; $http.post(text, query).success(function (data) { deferred.resolve(data); }); return deferred.promise; } resource.addBookmark = function (database, item) { var deferred = $q.defer(); DocumentApi.createDocument(database, item['@rid'], item, function (data) { deferred.resolve(data); }); return deferred.promise; } resource.refresh = function () { resource.tags = null; resource.changed = true; resource.changed = false; } resource.remove = function (database, bk) { var deferred = $q.defer(); DocumentApi.deleteDocument(database, bk['@rid'], function (data) { deferred.resolve(data); }); return deferred.promise; } resource.update = function (database, bk) { var deferred = $q.defer(); DocumentApi.updateDocument(database, bk['@rid'], bk, function (data) { deferred.resolve(data); }); return deferred.promise; } resource.getTags = function (database) { var deferred = $q.defer(); var text = API + 'command/' + database + '/sql/-/-1?format=rid,type,version,class,graph'; var query = 'select distinct(value) as value from ( select expand(tags) from {{clazz}})'; query = S(query).template({clazz: CLAZZ}).s; $http.post(text, query).success(function (data) { var model = []; angular.forEach(data.result, function (v, index) { model.push(v.value); }); deferred.resolve(model); }); return deferred.promise; } return resource; }); breadcrumb.factory('History', function ($resource, localStorageService, DocumentApi, $http, $q) { var resource = $resource(API + 'database/:database'); var CLAZZ = "_studio_history" resource.CLAZZ = CLAZZ; return resource; });
if(!guru.shapes.Circle) { guru.shapes.Circle = function(x, y, radius) { this._x = x; this._y = y; this._radius = radius; this._color = new guru.Color(); }; guru.shapes.Circle.prototype.setColor = function(color) { this._color = color; return this; }; guru.shapes.Circle.prototype.getPosition = function() { return { x: this._x, y: this._y }; }; guru.shapes.Circle.prototype.move = function(x, y) { this._x += x; this._y += y; return this; }; guru.shapes.Circle.prototype.render = function(context) { var oldStyle = context.fillStyle; context.fillStyle = this._color._css; context.beginPath(); context.arc(this._x, this._y, this._radius, 0, 2 * Math.PI, true); context.fill(); context.closePath(); context.fillStyle = oldStyle; return this; }; }
import React, { useEffect } from 'react'; import { FooterFour, HeaderFive, Wrapper } from '../../../layout'; import { animationCreate } from '../../../utils/utils'; import BlogArea from './blog-area'; import BrandArea from './brand-area'; import ClientFeedback from './client-feedback'; import FeatureArea from './feature-area'; import HeroArea from './hero-area'; import MissionArea from './mission-area'; import ProjectArea from './project-area'; import ServicesArea from './services-area'; import TeamArea from './team-area'; const HomeFive = () => { useEffect(() => { setTimeout(() => { animationCreate(); }, 500); }, []); return ( <Wrapper> <HeaderFive/> <HeroArea/> <FeatureArea/> <ServicesArea/> <MissionArea/> <BrandArea/> <ProjectArea/> <TeamArea/> <ClientFeedback/> <BlogArea/> <FooterFour/> </Wrapper> ); }; export default HomeFive;
var searchData= [ ['question',['Question',['../classindex_1_1models_1_1Question.html',1,'index::models']]], ['questionform',['QuestionForm',['../classindex_1_1forms_1_1QuestionForm.html',1,'index::forms']]], ['quiz',['Quiz',['../classindex_1_1models_1_1Quiz.html',1,'index::models']]], ['quizform',['QuizForm',['../classindex_1_1forms_1_1QuizForm.html',1,'index::forms']]] ];
var app = {} app.loginpage = Backbone.View.extend({ el: $('#right'), initialize: function() {}, events: { 'submit #formlogin': 'signinn', 'click #signup': 'signup', 'focus .inf': 'hideerror' }, render: function() { if (islogin()) myrouter.navigate('status', { trigger: true }); else { $(this.el).removeClass("col-sm-8").addClass("col-sm-12"); $(this.el).empty(); var data = $.ajax({ 'url': '/templates/loginpage.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); $(this.el).append(data.responseText); this.hideerror(); //return this; } }, signinn: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); var loginperson = {}; loginperson.email = $('#inputEmail').val(); loginperson.password = $('#inputPassword').val(); var loginM = new loginModel(); loginM.save(loginperson, { success: function(data) { console.log(data); data = data.toJSON(); console.log(data); if (data.errorCode == 0) { localStorage.setItem("sessionid", data.sessionId); //localStorage.setItem("userid",data.u_id); localStorage.setItem("statusProtype", "data.role"); myrouter.navigate('status', { trigger: true }); } else if (data.errorCode == 2 || data.errorCode == 19) { $('#le').show(); localStorage.setItem("sessionid", null); } }, error: function(returndata) { console.log("error in login API"); } }); }, signup: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); myrouter.navigate('signup', { trigger: true }); }, hideerror: function() { $('#le').hide(); } }); app.statuspage = Backbone.View.extend({ el: $('#right'), initialize: function() {}, events: { 'submit #taskform': 'submitTask', 'click #resetstatus': 'resetstatus', 'click .actionbtn': 'editupdatedtask', 'submit #userfilter': 'userfilter' }, render: function() { if (islogin()) { $(this.el).removeClass("col-sm-12").addClass("col-sm-8"); $('#left').show(); scope = this; // var home = new homeModel() // var p = { // "sessionid": localStorage.getItem("sessionid") // }; // home.save(p, { // success: function(returndata) { // returndata = returndata.toJSON(); // if(returndata.role=="admin") // { // var data = $.ajax({ // 'url': '/templates/adminpage.html', // 'async': false // }); // if (data.responseText != undefined && data.responseText != '') // var datac = Handlebars.compile(data.responseText); // $(scope.el).html(datac(returndata)); // $(".datepicker").datepicker(); // } // else // { // var data = $.ajax({ // 'url': '/templates/dailytaskpage.html', // 'async': false // }); // if (data.responseText != undefined && data.responseText != '') // var datac = Handlebars.compile(data.responseText); // $(this.el).html(datac); // var table1 = new app.tableview(); // table1.render(); // $(".datepicker").datepicker(); // } // }, // error: function(returndata) { // console.log("error filter:" + returndata); // } // }); if (localStorage.getItem("statusProtype") === "admin") { var admin = new adminModel() var p = { "sessionid": localStorage.getItem("sessionid") }; admin.save(p, { success: function(returndata) { returndata = returndata.toJSON(); var data = $.ajax({ 'url': '/templates/adminpage.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); $(scope.el).html(datac(returndata)); $(".datepicker").datepicker(); }, error: function(returndata) { console.log("error filter:" + returndata); } }); } else { // $('#date').prop('type', 'date'); //$("#date").prop('disabled', true); var data = $.ajax({ 'url': '/templates/dailytaskpage.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); $(this.el).html(datac); var table1 = new app.tableview(); table1.render(); } } else{ myrouter.navigate('login', { trigger: true }); } $('#Esubmit').hide(); console.log("i am here"); return this; }, dateformat: function(d) { d = new Date(d); //console.log("d1:"+d); var dd = d.getDate(); var mm = d.getMonth() + 1; var yyyy = d.getFullYear(); if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } d = yyyy + '-' + mm + '-' + dd; //console.log("d2:"+d); return d; }, userfilter: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); scope = this; n = $("#name").val(); s = $('#ssdate').val(); e = $('#eedate').val(); var p = { "sessionid": localStorage.getItem("sessionid") }; if (s !== "") s = this.dateformat(s); if (e !== "") e = this.dateformat(e); if (n != "A" && (s != "" || e != "")) { if (s == "") { s = "2000-01-01"; } else if (e == "") { var e = new Date(); e=this.dateformat(e); } p.userid = n; p.startdate = s; p.enddate = e; } else if (n == "A" && (s != "" || e != "")) { if (s == "") { s = "2000-01-01"; } else if (e == "") { var e = new Date(); e=this.dateformat(e); } p.startdate = s; p.enddate = e; } else if (n != "A") { p.userid = n; } if (Date.parse(s) > Date.parse(e)) { alert("choose valid date"); document.getElementById("userfilter").reset(); }else { var filter = new filtertaskModel() filter.save(p, { success: function(returndata) { returndata = returndata.toJSON(); var data = $.ajax({ 'url': '/templates/tasklistadmin.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); $("#adminbox").html(datac(returndata)); $("#admintable").dataTable({ //"bFilter" : false, "bLengthChange": false, "iDisplayLength": 5, "aoColumnDefs": [{ 'bSortable': false, 'aTargets': [1] }, { 'bSortable': false, 'aTargets': [3] }, { 'bSortable': false, 'aTargets': [4] }, { "sClass": "my_class", "aTargets": [0, 1, 2, 3, 4, 5] }] }); }, error: function(returndata) { console.log("error hh:" + returndata); } }); } }, submitTask: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); scope = this; var type = document.getElementById("submitTask").innerHTML; if (islogin()) { var newStatus = {}; newStatus.sessionId = localStorage.getItem("sessionid"); newStatus.type = type; newStatus.date = scope.dateformat(""+$('#date').val()); newStatus.task = $('#task').val(); newStatus.timeTaken = $('#time').val(); newStatus.pendingTask = $('#P_task').val(); console.log(newStatus); update = new updateTaskModel() update.save(newStatus, { success: function(returnData) { var d = returnData.toJSON(); $("#date").prop('disabled', false); document.getElementById("taskform").reset(); console.log("d.result1:" +d.result1); if (type== "Submit") { if (d.result === "success") new app.tableview().render(); else { $('#Esubmit').show(); new app.tableview().render(); } } else { new app.tableview().render(); document.getElementById("submitTask").innerHTML = "Submit"; } }, error: function(returndata) { console.log("error in UPDATE API"); } }); } else { myrouter.navigate('login', { trigger: true }); } }, resetstatus: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); document.getElementById("taskform").reset(); $('#Esubmit').hide(); }, editupdatedtask: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); if (islogin()) { $("#date").prop('disabled', true); $('#Esubmit').hide(); var i = event.target.id; console.log("edit clicked:" + i); $('#tsk' + i).attr('contentEditable', true); $('#tim' + i).attr('contentEditable', true); $('#ptask' + i).attr('contentEditable', true); var a = document.getElementById("dat" + i).innerHTML; var b = document.getElementById("tsk" + i).innerHTML; var c = document.getElementById("tim" + i).innerHTML; var d = document.getElementById("ptask" + i).innerHTML; document.getElementById("submitTask").innerHTML = "Update"; document.getElementById("date").value = a; document.getElementById("task").value = b; document.getElementById("time").value = c; document.getElementById("P_task").value = d; } else { myrouter.navigate('login', { trigger: true }); } } }); ////////// app.tasklist = Backbone.View.extend({ el: $('#right'), initialize: function() {}, events: { 'click .actionbtn': 'opentask' }, render: function() { $('#left').show(); $(this.el).removeClass("col-sm-12").addClass("col-sm-8"); if (islogin()){ var user = new UserModel(); var scope = this; user.fetch({ success: function(returndata) { var result = $.ajax({ 'url': '/templates/tasklist.html', 'async': false }); if (result.responseText != undefined && result.responseText != '') var compiledresult = Handlebars.compile(result.responseText); console.log("returndata:" + returndata.toJSON()); $(scope.el).html(compiledresult(returndata.toJSON())); } }) } else { myrouter.navigate('login', { trigger: true }); } return this; }, opentask: function(e) { var i = event.target.id; myrouter.navigate('singletask', { trigger: true }); } }); app.singletask = Backbone.View.extend({ el: $('#right'), initialize: function() {}, events: {}, render: function() { $(this.el).removeClass("col-sm-12").addClass("col-sm-8"); $('#left').show(); if (islogin()) { console.log("singletask"); scope = this; $('#right').empty(); var user = new UserModel2(); var scope = this; user.fetch({ success: function(returndata) { var result = $.ajax({ 'url': '/templates/singletask.html', 'async': false }); if (result.responseText != undefined && result.responseText != '') var compiledresult = Handlebars.compile(result.responseText); console.log("returndata:", returndata.toJSON()); $(scope.el).html(compiledresult(returndata.toJSON())); } }) } else { myrouter.navigate('login', { trigger: true }); } return this; }, opentask: function() { alert(); } }); ///////////////////////////////////// app.profilepage = Backbone.View.extend({ el: $('#right'), initialize: function() {}, events: { 'dblclick .editP': 'updateprofileF', 'click .update': 'updateprofileF2', 'click .edit': 'updateprofileF' }, render: function() { scope = this; console.log("in profile render"); if (islogin()) { $('#left').show(); $(this.el).removeClass("col-sm-12").addClass("col-sm-8"); var profile = new profileModel(); var p = { "sessionid": localStorage.getItem("sessionid") }; profile.save(p, { success: function(returndata) { console.log(returndata.toJSON()); var data = $.ajax({ 'url': '/templates/profilepage.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); console.log("returndata:" + returndata.toJSON()); $('#right').html(datac(returndata.toJSON())); // $('#update').hide(); }, error: function(returndata) { console.log("error:" + returndata); myrouter.navigate('status', { trigger: true }); } }); } else myrouter.navigate('login', { trigger: true }); return this; }, updateprofileF: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); var i = event.target.id; // console.log(i); $('.editP').prop('disabled', false).removeClass("inputfield"); $('#update').html("Update"); // console.log($('#update').innerHTML); // document.getElementById("update").innerHTML = "Update"; $('#update').addClass('update').removeClass('edit'); }, updateprofileF2: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); scope = this; var updateprofile = new updateprofileModel(); var p = { "sessionid": localStorage.getItem("sessionid") }; $('#update').innerHTML = "Update"; p.firstname = $('#fn').val(); p.lastname = $('#ln').val(); p.email = $('#eml').val(); p.alteremail = ($('#aeml').val() == undefined) ? "" : $('#aeml').val(); p.empid = $('#emp').val(); p.mobileno = $('#mn').val(); p.username = $('#un').val(); p.altermobileno = ($('#amn').val() == undefined) ? "" : $('#amn').val(); if (validateEmail(p)) { console.log("here"); updateprofile.save(p, { success: function(returndata) { console.log(returndata); scope.render(); $('#update').html("Edit"); $('#update').addClass('edit').removeClass('update'); }, error: function(returndata) { console.log("error:" + returndata); myrouter.navigate('status', { trigger: true }); } }); } else alert("invalid entry"); } }); /////////////////////////// app.tableview = Backbone.View.extend({ el: $('#tablebox'), initialize: function() { //this.model.on('change', _.bind(this.render, this)) }, events: {}, render: function() { scope = this; console.log("in table render"); //task = new taskModel(); if (islogin()) { // setInterval(function(){ // collection.fetch(); // },30000); task.save({ "sessionid": localStorage.getItem("sessionid") }, { success: function(returndata) { var tasklist = returndata.toJSON(); var data = $.ajax({ 'url': '/templates/statuslist.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); console.log("taskdata: " + tasklist); $('#tablebox').html(datac(tasklist)); }, error: function(returndata) { console.log("error:" + returndata); } }); } else { myrouter.navigate('login', { trigger: true }); } return this; } }); app.createtask = Backbone.View.extend({ el: $('#right'), initialize: function() {}, events: { 'focus .enddate': 'abc', 'submit #taskform': 'assign' }, render: function() { scope = this; console.log("in create render"); task = new taskModel(); if (islogin()) { $('#left').show(); $(this.el).removeClass("col-sm-12").addClass("col-sm-8"); var user = new UserModel0(); user.fetch({ success: function(returndata) { console.log(returndata); console.log(returndata.toJSON()); var data = $.ajax({ 'url': '/templates/createtaskpage.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); //console.log("taskdata: " + tasklist); $(scope.el).html(datac(returndata.toJSON())); } }) } return this; }, assign: function() { console.log("assigned"); var p = { "sessionid": localStorage.getItem("sessionid") }; p.useId = $('#user').val(); p.deadLine = new app.statuspage().dateformat($('#enddate').val()); p.task = $('#ctask').val(); p.comment = $('#ccomment').val(); var today = new Date(); p.assignDate = new app.statuspage().dateformat(today); console.log("a:" + p.deadLine); console.log("b:" + p.assignDate); console.log(p); }, abc: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); $('#enddate').datepicker(); console.log("date abc"); } }); ///////////////////////////////////////// app.signuppage = Backbone.View.extend({ el: $('#right'), initialize: function() {}, events: { 'submit #frm': 'register', 'focus .infs': 'hideerror' }, render: function() { if (islogin()) myrouter.navigate('status', { trigger: true }); else { $(this.el).removeClass("col-sm-8").addClass("col-sm-12"); $('#left').hide(); var data = $.ajax({ 'url': '/templates/signuppage.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); $(this.el).html(datac); $('#sup').hide(); $('#signup_cnf_pass-location').hide(); //return this; } }, register: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); var pass1 = $('#pwd').val(); var pass2 = $('#repwd').val(); var status = true; if (pass1 != pass2) { $('#signup_cnf_pass-location').show(); status = false; } if (status === true) { $('#signup_cnf_pass-location').hide(); var newPerson = {}; newPerson.firstName = $('#fname').val(); newPerson.lastName = $('#lname').val(); newPerson.email = $('#email').val(); newPerson.alterEmail = $('#aemail').val(); newPerson.uid = $('#empid').val(); newPerson.password = $('#pwd').val(); newPerson.mobileNum = $('#mobile').val(); newPerson.alterMobileNum = $('#amobile').val(); newModel = new signupModel(); newModel.save(newPerson, { success: function(returnData) { var data = returnData.toJSON() if (data.errorCode == 0) { alert("You are registered now Please Login"); myrouter.navigate('login', { trigger: true }); }else if(data.errorCode==1) { $('#sup').show(); } }, error: function(data) { console.log("error in signupAPI"); } }); } }, hideerror: function() { $('#signup_cnf_pass-location').hide(); } }); ///////////////////////////////// app.notyboxView = Backbone.View.extend({ el: $('#tt'), initialize: function() { //this.model.on('change', _.bind(this.render, this)) }, events: { "mouseover":'newnoty', "click .rowssr" : "notyclick", "mouseout":'removenewnoty', 'click .notificationcount':'notyfunction' }, render: function(id) { scope = this; console.log("in notyview render"); var arr =["Apple","Apricot","Avocado","Goji berry","Grape","Raisin","Grapefruit"]; var data = $.ajax({ 'url': '/templates/noty.html', 'async': false }); if (data.responseText != undefined && data.responseText != '') var datac = Handlebars.compile(data.responseText); $(this.el).html(datac(arr)); this.pos(id); return this; }, pos:function(i){ var el1=document.getElementById(i); var el2=document.getElementById("tt"); var X = el1.offsetLeft; var Y= el1.offsetTop; var w= el1.offsetWidth; var h= el1.offsetHeight; $('#tt').css( { 'position': 'absolute', 'right': 50, 'top': Y+h+20, 'width':100 }); }, newnoty:function(e){ $(e).addClass('newnoty'); }, removenewnoty:function(e){ $(e).removeClass('newnoty'); }, notyfunction:function(){ if($('#tt').css('display') == 'none') { new app.notyboxView().render(id); $('#tt').show(); } else { $('#tt').hide(); } }, notyclick:function(e) { myrouter.navigate('singletask', { trigger: true }); } }); ////////////////////////// function logout5() { $('#left').hide(); logoutM = new logoutModel(); logoutM.save({"sessionid": localStorage.getItem("sessionid")},{ success: function(data) { localStorage.setItem("sessionid", null); myrouter.navigate('login', { trigger: true }); }, error: function(returndata) { console.log("error not found:" + returndata); } }); } function notyfunction(id) { if($('#tt').css('display') == 'none') { new app.notyboxView().render(id); $('#tt').show(); } else { $('#tt').hide(); } } $('html').click(function() { $('#tt').hide(); }); function profile5() { $('#left').show(); myrouter.navigate('profile', { trigger: true }); } function home5() { myrouter.navigate('status', { trigger: true }); } function createTask() { myrouter.navigate('createtask', { trigger: true }); } function taskList() { myrouter.navigate('tasklist', { trigger: true }); } function validateEmail(obj) { if (obj.mobileno.length < 10) { alert("mobile no. is invalid") return false; } if (obj.altermobileno.length < 10 && obj.altermobileno.length != 0) { alert("alternate mobile no. is invalid") return false; } var re_number = /^\d*$/; var re_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re_number.test(obj.mobileno) && re_email.test(obj.email) && re_number.test(obj.altermobileno) && re_email.test(obj.alteremail); } $(window).scroll(function() { var scrollTop = 70; if ($(window).width() > 768 && $(window).scrollTop() >= scrollTop) { $('#sidebar12').addClass('navbar1'); } if ($(window).scrollTop() <= scrollTop) { $("#sidebar12").removeClass('navbar1'); } }); Handlebars.registerHelper("changeDate", function(date) { date = new Date(date); var dd = date.getDate(); var mm = date.getMonth() + 1; var yyyy = date.getFullYear(); if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } date = yyyy + '-' + mm + '-' + dd; return date; }) window.onload = function (){ if(!!window.EventSource) { var source = new EventSource('http://192.168.1.113:3005/events'); console.log("yes"+source); source.onmessage =function(e) { console.log("yes in"+source); //document.body.innerHTML += e.data + '<br>'; }; } else { // Result to xhr polling :( console.log("no"); } } exports = app;
// Copyright 2012 Dmitry Monin. 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. /** * @fileoverview Toggle button */ goog.provide('morning.ui.ToggleButton'); goog.require('goog.dom.classlist'); goog.require('goog.ui.registry'); goog.require('morning.ui.Button'); /** * Toggle button * * @constructor * @extends {morning.ui.Button} */ morning.ui.ToggleButton = function() { goog.base(this); /** * @type {boolean} * @protected */ this.isPressed_ = false; }; goog.inherits(morning.ui.ToggleButton, morning.ui.Button); /** @inheritDoc */ morning.ui.ToggleButton.prototype.enterDocument = function() { goog.base(this, 'enterDocument'); this.getHandler().listen(this, goog.ui.Component.EventType.ACTION, this.handleAction_); }; /** * Returns click handler event * * @return {Element} */ morning.ui.ToggleButton.prototype.getHandlerElement = function() { return this.getElement(); }; /** * Handles action event * * @param {goog.events.BrowserEvent} e * @private */ morning.ui.ToggleButton.prototype.handleAction_ = function(e) { if (this.isPressed_) { this.remove(); } else { this.add(); } }; /** * Performs add action * @protected */ morning.ui.ToggleButton.prototype.add = function() { this.setPressed(true); }; /** * Returns true if button is pressed * * @return {boolean} */ morning.ui.ToggleButton.prototype.isPressed = function() { return this.isPressed_; }; /** * Performs remove action * @protected */ morning.ui.ToggleButton.prototype.remove = function() { this.setPressed(false); }; /** * Sets button pressed state * * @param {boolean} isPressed */ morning.ui.ToggleButton.prototype.setPressed = function(isPressed) { this.isPressed_ = isPressed; if (this.getElement() !== null) { goog.dom.classlist.enable(this.getElement(), 'pressed', isPressed); } };
import Router from "next/router"; import styled from "styled-components"; import WorkCard from "./components/WorkCard"; const Grid = styled.div` display: grid; grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr 1fr; grid-row-gap: 3rem; grid-column-gap: 3rem; @media screen and (max-width: 700px) { grid-template-rows: 1fr; grid-template-columns: auto; grid-row-gap: 1rem; grid-column-gap: 1rem; } `; const Section = styled.section` .not--active:hover { transform: scale(1.1); box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22); } .portfolio__item__content a { cursor: pointer; } .i1 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 1; grid-row-end: 2; } .i2 { grid-column-start: 2; grid-column-end: 3; grid-row-start: 1; grid-row-end: 2; } .i3 { grid-column-start: 3; grid-column-end: 4; grid-row-start: 1; grid-row-end: 2; } .i4 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 2; grid-row-end: 3; } .i5 { grid-column-start: 2; grid-column-end: 3; grid-row-start: 2; grid-row-end: 3; } .i6 { grid-column-start: 3; grid-column-end: 4; grid-row-start: 2; grid-row-end: 3; } .i7 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 3; grid-row-end: 4; } .i8 { grid-column-start: 2; grid-column-end: 3; grid-row-start: 3; grid-row-end: 4; } .i9 { grid-column-start: 3; grid-column-end: 4; grid-row-start: 3; grid-row-end: 4; } .active { z-index: 100; grid-column: 1/4; grid-row: 1/4; transform: none; } @media screen and (max-width: 700px) { .not--active:hover { transform: none; box-shadow: none; } .active { z-index: 3; height: 100vh; width: 100vw; transform: none; position: fixed; top: 0; left: 0; border-radius: 0; padding: 10vh 1rem 1rem 1rem; } .i1 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 1; grid-row-end: 2; } .i2 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 2; grid-row-end: 3; } .i3 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 3; grid-row-end: 4; } .i4 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 4; grid-row-end: 5; } .i5 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 5; grid-row-end: 6; } .i6 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 6; grid-row-end: 7; } .i7 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 7; grid-row-end: 8; } .i8 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 8; grid-row-end: 9; } .i9 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 9; grid-row-end: 10; } .portfolio__item { min-height: 20vh; } } `; const data = [ "http://distracted-goldwasser-aaeb24.bitballoon.com/", "http://practical-wright-58b89a.bitballoon.com/", "#", "#", "http://nervous-mclean-17152f.bitballoon.com/", "#", "#", "#", "https://relaxed-poincare-7d9478.netlify.com/" ]; class WorkComponent extends React.Component { state = { active: null }; selectActive = selection => { this.setState({ active: selection }); }; render() { const { active } = this.state; console.log(active, active === 4 ? "active" : "null"); return ( <Section> <Grid className="portfolio"> {data.map((data, i) => ( <WorkCard selectActive={this.selectActive} active={active} url={data} i={i} /> ))} </Grid> </Section> ); } } export default WorkComponent;
var fs = require('fs'); var chalk = require('chalk'); process.stdout.write(chalk.yellow('prompt > ')); var done = function(output) { process.stdout.write(chalk.blue(output)); process.stdout.write(chalk.yellow('\nprompt > ')); } var commands = { done: function(output) { process.stdout.write(chalk.blue(output)); process.stdout.write(chalk.yellow('\nprompt > ')); }, ls: function() { var output = ""; fs.readdir('.', function(err, files) { files.forEach(function(file) { output += file.toString() + "\n"; }) done(output); }); }, pwd: function() { var output = ""; fs.readdir('.', function(err, files) { files.forEach(function(file) { output += file.toString() + "\n"; }) done(output); }); } } var obj = { pwd: function(){ process.stdin.on('data', function (data) { var cmd = data.toString().trim().split(' '); // remove the newline if(cmd[0] == "pwd") { process.stdout.write(chalk.blue(process.cwd())); } else if(cmd[0] == "date") { process.stdout.write(chalk.cyan((new Date()).toString())); } else if(cmd[0] == "ls") { chalk.red(fs.readdir('.', function(err, file){ if(err) throw err; process.stdout.write(file.toString().replace(/,/g , " ")); })); } else if(cmd[0] == "echo") { if(cmd[1][0] == "$"){ process.stdout.write(chalk.magenta(process.env[cmd[1].slice(1)])); } else process.stdout.write(cmd.slice(1).toString().replace(/,/g , " ")); } else if(cmd[0] == "cat") { fs.readFile(cmd[1], 'utf8', function(err, file){ if(err) throw err; console.log(file); }) } else if(cmd[0] == "head") { fs.readFile(cmd[1], 'utf8', function(err, file){ if(err) throw err; var file_array = file.split('\n'); for(var i = 0; i < 5; i++){ console.log(file_array[i]); } }) } else if(cmd[0] == "tail") { fs.readFile(cmd[1], 'utf8', function(err, file){ if(err) throw err; var file_array = file.split('\n'); for(var i = file_array.length-5; i < file_array.length; i++){ console.log(file_array[i]); } }) } else { process.stdout.write('You typed: ' + cmd); } process.stdout.write(chalk.yellow('\nprompt > ')); }); } } module.exports=commands
import React, {useEffect} from 'react'; import Header from "../components/Header/Header"; import {Container} from "@material-ui/core"; import {useStyles} from "./styled"; import {fetchUsersFetching} from "../store/users/actions"; import {useDispatch} from "react-redux"; import UsersList from "../containers/UsersList/UsersList"; const UsersPage = () => { const classes = useStyles(); const dispatch = useDispatch() useEffect(() => { dispatch(fetchUsersFetching()) }, []); return ( <Container className={classes.rootCentered}> <Header/> <UsersList/> </Container> ); }; export default UsersPage;
const path = require("path"); module.exports.studentHomePage = function(req, res){ dispatchPage("index", res); } module.exports.studentProfilePage = function(req, res){ dispatchPage("profile", res); } module.exports.studentLoginPage = function(req, res){ dispatchPage("login", res); } module.exports.studentAttendacePage = function(req, res){ dispatchPage("attendace", res); } module.exports.studnetUpdatePage = function(req, res){ dispatchPage("student-update", res); } module.exports.studentQrCode = function(req, res){ dispatchPage("student-qr", res); } dispatchPage = function(pageName, res){ res.status(200).sendFile(path.join(__dirname, "..", "..", "public", "student" ,pageName+".html") ); }
import GetCurrentPositionAction from '../../src/actions/GetCurrentPositionAction.js' describe('GetCurrentPositionAction', () => { it('gets the current map position from a service', () => { const IpLocationService = { run: () => Promise.resolve({latitude: 0, longitude: 0}) } sinon.spy(IpLocationService, 'run') const action = GetCurrentPositionAction(IpLocationService) return action.run().then((position) => { expect(position).to.deep.eq({lat: 0, lng: 0}) }) }) })
export default class User { static register(mongoose) { let UserSchema = new mongoose.Schema({ first_name: {type: String, default: ''}, last_name: {type: String, default: ''}, username: {type: String, default: '', trim: true, unique: true}, email: {type: String, default: ''}, password: {type: String, default: ''}, mobile: { country_code: {type: String, default: ''}, number: {type: String, default: ''}, is_verified: {type: Boolean, default: false}, verification_code: {type: String} }, blogs: [{type: mongoose.Schema.Types.ObjectId, ref: 'Blog'}], profile_img: {type: String, default: ''} }); UserSchema.virtual('id').get(function () { return this._id; }); UserSchema.set('toJSON', {virtuals: true}); UserSchema.set('toObject', {virtuals: true}); mongoose.model('User', UserSchema); } }
import React from "react"; import { View, StyleSheet, Text, Button, SafeAreaView, Alert, TouchableOpacity } from 'react-native'; import ScheduleItem from "../../components/ForVlad/ScheduleItem"; import SelectDay from "../../components/ForVlad/SelectDay"; class ForVlad extends React.Component { constructor () { super(); this.state = { group: 1, day: 0, week: 0, weekC: 1, weekZ: 0, schedule: [ { name: 'НП з ОП', timeFrom: ' 9:30', timeTo: '10:55', day: 0, week: [-1], classroom: '25', group: 0 }, { name: 'Математика', timeFrom: '11:05', timeTo: '12:30', day: 0, week: [0], classroom: '25' }, { name: 'Українська мова', dateFrom: '11:05', timeTo: '12:30', day: 0, week: [1], classroom: '25'}, { name: 'Фізкультура', timeFrom: '12:50', timeTo: '14:15', day: 0, week: [0], classroom: 'С' }, { name: 'Фізика', timeFrom: '12:50', timeTo: '14:15', day: 0, week: [1], classroom: '25' }, { name: 'Українська мова', timeFrom: '14:25', timeTo: '15:50', day: 0, week: [0], classroom: '25', weekC: [0]}, //Tuesday { name: 'НП з ОП', timeFrom: ' 9:30', timeTo: '10:55', day: 1, week: [-1], classroom: 26, group: 1 }, { name: 'Економіка', timeFrom: '11:05', timeTo: '12:30', day: 1, week: [-1], classroom: 25 }, { name: 'Екологія', timeFrom: '12:50', timeTo: '14:15', day: 1, week: [-1], classroom: 25 }, //s { name: 'Укр. літ.', timeFrom: ' 9:30', timeTo: '10:55', day: 2, week: [-1], classroom: 25 }, { name: 'Англ. мова', timeFrom: '11:05', timeTo: '12:30', day: 2, week: [-1], classroom: 25 }, { name: 'НП з ОП', timeFrom: '12:50', timeTo: '14:15', day: 2, week: [-1], classroom: 25 }, //t { name: 'ОП та алг.', timeFrom: ' 9:30', timeTo: '10:55', day: 3, week: [-1], classroom: 22, group: 1 }, { name: 'Оп та алг.', timeFrom: '11:05', timeTo: '12:30', day: 3, week: [-1], classroom: 25 }, { name: 'Фізика', timeFrom: '12:50', timeTo: '14:15', day: 3, week: [-1], classroom: '25/33' }, { name: 'Фізкультура', timeFrom: '14:25', timeTo: '15:50', day: 3, week: [-1], classroom: 'C' }, { name: 'Математика', timeFrom: ' 9:30', timeTo: '10:55', day: 4, week: [-1], classroom: 25 }, { name: 'НП з ОП', timeFrom: '11:05', timeTo: '12:30', day: 4, week: [-1], classroom: 26, group: 1 }, { name: 'ОП та алг.', timeFrom: '11:05', timeTo: '12:50', day: 4, week: [-1], classroom: 23, group: 0 }, { name: 'Іст. України', timeFrom: '12:50', timeTo: '14:15', day: 4, week: [-1], classroom: 25 }, ] } } render () { const table = []; for (let i in this.state.schedule) { const item = this.state.schedule[i]; if (item.day != this.state.day) continue; if (item.group != undefined) if (item.group != this.state.group) continue; if (item.week[0] != -1) if (item.week.includes(this.state.week) == false) continue; if (item.weekC) if (item.weekC != this.state.weekC) continue; if (item.weekZ) if (item.weekZ != this.state.weekZ) continue; table.push(<ScheduleItem data={item} key={i} />); } return ( <View style={styles.container}> <View style={styles.days}> <SelectDay changeDay={this.changeDay} active={ this.state.day == 0?true: false } day={0} title="П"/> <SelectDay changeDay={this.changeDay} active={ this.state.day == 1?true: false } day={1} title="В"/> <SelectDay changeDay={this.changeDay} active={ this.state.day == 2?true: false } day={2} title="С"/> <SelectDay changeDay={this.changeDay} active={ this.state.day == 3?true: false } day={3} title="Ч"/> <SelectDay changeDay={this.changeDay} active={ this.state.day == 4?true: false } day={4} title="П"/> </View> <View style={styles.table}> {table} </View> </View> ) } changeDay = (day) => { this.setState({ day: day }); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#292929' }, text: { color: 'red', fontSize: 20, }, days: { flex: 0, width: '100%', height: 30, flexDirection: 'row', }, day: { width: '20%', height: '100%', backgroundColor: '#292929', borderTopWidth: 0, borderLeftWidth: 0, borderRightWidth: 2, borderColor: '#000000', borderWidth: 2, }, textDay: { color: '#808080', textAlign: 'center', fontSize: 17, fontWeight: 'bold', }, table: { width: '100%', height: '100%' }, textSet: { color: '#808080', } }); export default ForVlad;
/* * Experiments * https://github.com/epentangelo/JavaScriptExperiments * * Copyright (c) 2014 holoed * Licensed under the MIT license. */ 'use strict'; var _ = require('underscore'); var rx = require('rx'); exports.awesome = function() { return 'awesome'; }; exports.sequence = function(source) { return _.foldl(source, function(acc, x) { return acc.selectMany(function(accp) { return x; } , function (x1, x2) { return x1.concat([x2]); } ); }, rx.Observable.just([])); };
function countdown(time){ var countTo = new Date(); countTo.setSeconds(countTo.getSeconds() + time); var countDownDate = countTo.getTime(); var countdown = setInterval(function(){ var now = new Date().getTime(); var delta = countDownDate - now; var minutes = Math.floor((delta % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((delta % (1000 * 60)) / 1000); document.getElementById("countdown").innerHTML = minutes + ":" + seconds; if(delta < 0){ clearInterval(countdown); document.getElementById("countdown").innerHTML = "Quelques secondes..."; } }, 1000); };
'use strict'; /** This script is run whenever the devtools are open. In here, we can create our panel. */ let count = 0; function check_page_for_opal() { chrome.devtools.inspectedWindow.eval( `var framework = null; var opal_version = null; var devtools_support = false; if (typeof Opal !== "undefined") { opal_version = Opal.RUBY_ENGINE_VERSION; if (typeof Opal.Isomorfeus !== "undefined") { framework = "isomorfeus" } else if (typeof Opal.Hyperstack !== "undefined") { framework = "hyperstack" } else if (typeof Opal.Hyperloop !== "undefined") { framework = "hyperloop" } else if (typeof Opal.Clearwater !== "undefined") { framework = "clearwater" } if (typeof Opal.opal_devtools_object_registry !== "undefined") { devtools_support = true } } [opal_version, framework, devtools_support]`, {}, function(res, error) { if (!res[0] && count < 6) { // browser possibly did not finish loading the page, so try again. count++; setTimeout(function() { check_page_for_opal(); }, 1000); } else { count = 0; let event = new CustomEvent('OpalDevtoolsPageCheck', {detail: {opal_version: res[0], framework: res[1], devtools_support: res[2]}}); panel_window.dispatchEvent(event); } }); } let panel_window = null; function handleShown(p_window) { panel_window = p_window; check_page_for_opal(); chrome.devtools.network.onNavigated.addListener(check_page_for_opal); } function handleHidden() { chrome.devtools.network.onNavigated.removeListener(check_page_for_opal); } chrome.devtools.network.onNavigated.addListener(check_page_for_opal); /** Create a panel, and add listeners for panel show/hide events. */ chrome.devtools.panels.create( "Opal", "/icons/opal_devtools_48.png", "/devtools/panel/panel.html", function(panel) { panel.onShown.addListener(handleShown); panel.onHidden.addListener(handleHidden); /** communicate with page */ chrome.runtime.onConnect.addListener(function(port) { port.onMessage.addListener(function (message, sender) { if (panel_window && message.tabId && message.fromConsole) { let event = new CustomEvent('OpalDevtoolsResult', { detail: message }); panel_window.dispatchEvent(event); } }); }); chrome.runtime.connect({name: "opal-devtools-page"}); });
import React, { useState } from 'react'; import { makeStyles } from '@material-ui/core/styles' import Button from '@material-ui/core/Button' import TextField from '@material-ui/core/TextField' import Input from '@material-ui/core/Input' import Typography from '@material-ui/core/Typography' import FormControl from '@material-ui/core/FormControl' import CloudUploadIcon from '@material-ui/icons/CloudUpload' import axios from 'axios' const useStyles = makeStyles((theme) => ({ root: { display: 'flex', flexWrap: 'wrap', }, input: { margin: theme.spacing(1), }, margin: { margin: theme.spacing(1), } })); export default function AddArtwork () { const [title, setTitle] = useState('') const [medium, setMedium] = useState('') const [dimensions, setDimensions] = useState('') const [source, setSource] = useState('') const [date, setDate] = useState('') const [path, setPath] = useState('') const classes = useStyles(); const handleSubmit = (e) => { e.preventDefault() const fileName = `${path}/${source}` console.log('fileName: ', fileName) axios.post('http://localhost:8888/add', { src: fileName, title, medium, dimensions, date }) .then(() => { window.location.href = 'https://ciara-post-portfolio.web.app/add' }) } const handleUpload = (e) => { console.log(e.target.files[0].name) setSource(e.target.files[0].name) } return ( <form className={classes.root} onSubmit={handleSubmit} noValidate> <TextField className={classes.input} label="Title" variant="outlined" name="title" value={title} onChange={(e) => setTitle(e.target.value)} /> <TextField className={classes.input} label="Medium" variant="outlined" name="medium" value={medium} onChange={(e) => setMedium(e.target.value)} /> <TextField className={classes.input} label="Dimensions" variant="outlined" name="dimensions" value={dimensions} onChange={(e) => setDimensions(e.target.value)} /> <TextField className={classes.input} label="Date" variant="outlined" name="date" value={date} onChange={(e) => setDate(e.target.value)} /> <TextField className={classes.input} label="Path" variant="outlined" name="path" value={path} onChange={(e) => setPath(e.target.value)} helperText="ex: for BAThesis/Ciara-Post-3.jpg, enter BAThesis" /> <FormControl> <Input accept="image/*" style={{ display: 'none' }} id="file-button" type="file" onChange={handleUpload} /> <label htmlFor="file-button"> <Button variant="contained" color="default" component="span" className={classes.margin} startIcon={<CloudUploadIcon />} > Upload </Button> </label> <Typography>{source}</Typography> </FormControl> <Button className={classes.margin} type='submit' value='Submit' variant='contained' > Submit </Button> </form> ); }
'use strict'; const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) => { class tasks_test extends Model { /** * Helper method for defining associations. * This method is not a part of Sequelize lifecycle. * The `models/index` file will call this method automatically. */ static associate(models) { // define association here tasks_test.hasMany(models.files_test,{ scope:{ belongsTo: models.tasks_test.getTableName(), belongsToColumn: 'fileUpload', } }) } }; tasks_test.init({ tasks_name: DataTypes.STRING }, { sequelize, modelName: 'tasks_test', }); return tasks_test; };
// JScript 文件 function returnfalse() { return false; } function checkdata(shopID) { if($('#DDL_Popseat').val()=="0") { $.prompt("请选择POP画面的位置!"); $('#DDL_Popseat').focus(); return false; } if($.trim($('#txt_seatNum').val())=="") { $.prompt("请正确填写POP编号!"); $('#txt_seatNum').focus(); return false; } if($.trim($('#txt_SeatDesc').val())=="") { $.prompt("请正确填写位置描述!"); $('#txt_SeatDesc').focus(); return false; } if($('#DDL_sexarea').val()=="0") { $.prompt("请选择男女区域!"); $('#DDL_sexarea').focus(); return false; } if(!isnumber($.trim($('#txt_realwidth').val()))) { $.prompt("请正确填写POP实际制作宽!只能为数字"); $('#txt_realwidth').focus(); return false; } if(!isnumber($.trim($('#txt_realheight').val()))) { $.prompt("请正确填写POP实际制作高!只能为数字"); $('#txt_realheight').focus(); return false; } if($.trim($('#txt_POPWith').val())=='') { $.prompt("请正确填写POP可视画面宽!"); $('#txt_POPWith').focus(); return false; } else { if(!isnumber($.trim($('#txt_POPWith').val()))) { $.prompt("请正确填写POP可视画面宽!只能为数字"); $('#txt_POPWith').focus(); return false; } } if($.trim($('#txt_POPHeight').val())=='') { $.prompt("请正确填写POP可视画面高!"); $('#txt_POPHeight').focus(); return false; } else { if(!isnumber($.trim($('#txt_POPHeight').val()))) { $.prompt("请正确填写POP可视画面高!只能为数字"); $('#txt_POPHeight').focus(); return false; } } if($('#DDL_plwz').val()=='0') { $.prompt("请选择POP可视画面偏离位置"); $('#DDL_plwz').focus(); return false; } if($('#DDL_pljd').val()=='-1') { $.prompt("请选择POP可视画面偏离角度"); $('#DDL_pljd').focus(); return false; } if($('#DDL_POPMaterial').val()=="0") { $.prompt("请正确填写POP的材质"); $('#DDL_POPMaterial').focus(); return false; } else if($('#DDL_POPMaterial').val()=="其他") { if($.trim($('#txt_POPMaterialRemark').val()) == "") { $.prompt("请输入POP备注说明!!"); $('#txt_POPMaterialRemark').focus(); return false; } } if($('#DDL_ProductLine').val()=="0") { $.prompt("请正确填写POP的产品系列"); $('#DDL_ProductLine').focus(); return false; } if(!isint($.trim($('#txt_PlatformLong').val()))) { $.prompt("请正确填写橱窗空间进深!只能为数字"); $('#txt_PlatformLong').focus(); return false; } if(!isint($.trim($('#txt_PlatformWith').val()))) { $.prompt("请正确填写橱窗空间长度!只能为数字"); $('#txt_PlatformWith').focus(); return false; } if(!isint($.trim($('#txt_PlatformHeight').val()))) { $.prompt("请正确填写橱窗面积!只能为数字"); $('#txt_PlatformHeight').focus(); return false; } if($('#FupPOPImg1').val()=='' && $('#FupPOPImg2').val()=='' && $('#FupPOPImg3').val()=='') { $.prompt("请您上传相关图片"); return false; } return true; } function getProductLine() { var typeid=$("#DDL_ProductType").val(); var url='ashx/GetPOPProductByType.ashx'; if(typeid=='0') { $("#DDL_ProductLine").empty(); $("<option value=0>请选择POP的产品系列</option>").appendTo($("#DDL_ProductLine")) } else { $.getJSON(url,{typeid:typeid},function(list) { $("#DDL_ProductLine").empty(); var plist="<option value=0>请选择POP的产品系列</option>"; for(var i=0;i<list.length;i++) { if(list[i].pid!="0") plist+="<option value="+list[i].pid+">"+list[i].linename+"</option>" } $(plist).appendTo($("#DDL_ProductLine")) }) } }
import Header from "./components/Header"; import "./App.scss"; import Modals from "./components/Modals"; import TaskContainer from "./containers/TaskContainer"; import SearchTask from "./components/SearchTask"; import LocalStorageContainer from "./containers/LocalStorageContainer"; function App() { return ( <div className="app"> <Header> <SearchTask/> <LocalStorageContainer/> </Header> <div className="app__wrapper"> <TaskContainer/> <Modals/> </div> </div> ); } export default App;
import instance from './axiosConfig'; function createSearchQuery(page, firstName, lastName, country, city) { let queryParameter = {} if (page !== "") queryParameter.page = page; if (firstName !== "") queryParameter.firstName = firstName; if (lastName !== "") queryParameter.lastName = lastName; if (country !== "") queryParameter.country = country; if (city !== "") queryParameter.city = city; return queryParameter; } export function getPeople(token, page, firstName, lastName, country, city) { try { return instance.get('/people', { params: createSearchQuery(page, firstName, lastName, country, city), headers: {"Authorization" : `Bearer ${token}`} }); } catch (error) { console.log(error); } }
/* * @lc app=leetcode.cn id=274 lang=javascript * * [274] H 指数 */ // @lc code=start /** * @param {number[]} citations * @return {number} */ // 0 1 3 5 6 // len = 5 var hIndex = function(citations) { citations = citations.sort((a, b) => {return a - b}); var i = 0; var len = citations.length; while (i < len && citations[len - 1 - i] > i) { // 倒序 i++ } return i; }; // @lc code=end
window._ = require('lodash'); window.Vue = require('vue'); window.axios = require('axios'); window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': window.Laravel.csrfToken, 'X-Requested-With': 'XMLHttpRequest' }; window.$ = window.jQuery = require('jquery'); //懒加载***** function echo() { var img = $('img'); var aImg = []; for(var i=0,j=0; i<img.length; i++){ if( img.eq(i).attr('data-img') ){ aImg[j++] = img[i];//.attr('data-img'); } } window.onscroll = ScrollTop; function ScrollTop(){/*滚动触发,上下滑动*/ for(var i=0; i<aImg.length; i++){ var top = []; top[i] = $(aImg[0]).offset().top - window.pageYOffset; //window.innerHeight-50图片距顶部多少像素就加载 if( top[i] < (window.innerHeight-50) && top[i] > 0){ aImg[i].src = $(aImg[0]).data('img'); $(aImg[0]).addClass('fade-in'); aImg.splice(i,1);//加载完清除 i--; } } }ScrollTop(); } echo(); //价钱小数点之后字体变小 var price = $('.price-decimal-point'); for(var i=0; i<price.length; i++){ var s = price.eq(i).text().replace(/\.([\d\.]*)/,'<span style="font-size:.9rem;letter-spacing:-1px;">.'+'$1'+'</span>'); price.eq(i).html('<i class="icon icon-money"></i>'+s); } $('#historyPageGo').click(function(){ window.history.go(-1);//返回上一页 }); $('#previous_page').click(function(){ window.history.go(-1);//返回上一页 }); $('#previous_f5').click(function(){ window.location.href = document.referrer;//返回上一页并刷新 }); //弹出菜单*** var $actionsheet = $('#actionsheet'); var $iosMask = $('#iosMask'); function hideActionSheet() {//关闭 $actionsheet.css({'-webkit-transform': 'translate3d(0,102%,0)','transform': 'translate3d(0,102%,0)'}); $iosMask.css('display','none'); } $iosMask.on('click', hideActionSheet); $('#iosActionsheetCancel').on('click', hideActionSheet); $(".showIOSActionSheet").on("click", function(){//显示 $actionsheet.css({'-webkit-transform': 'translate(0)','transform': 'translate(0)'}); $iosMask.css('display','block'); }); //编辑商品 var p = $('.price span').text(); p=parseFloat(p); p=p.toFixed(2);//小数点保留两位 function prices(n){ var p2=p*n; p2=p2.toFixed(2);//小数点保留两位 $('.price span').text(p2); } $(".add").click(function() { var num = parseInt($(this).prev().val()) + 1; if( num > $(this).prev().data().max )return;//不能小于data-max $(this).prev().val( num ); }); $(".min").click(function() { var num = parseInt($(this).next().val())-1; if(num<1)return;//不能小于1 $(this).next().val(num); }); //选择类型****************************** var target = $('.class-ok .attr-target'); var input = $('.attr-value'); input.click(selectAttr); function selectAttr(){ var s = ''; $('.attr-value:checked').each(function(index,elem){ s += $(this).next().text()+', '; }); s=s.replace(/, +$/,''); target.text(s); }selectAttr(); //添加 class="off-number" 出现已售罄 ************************************ var yishouqing = '<div class="off"><!--已售罄-->\ <i class="icon icon-yishouqing"><!--已售罄--></i>\ </div>'; $('.off-number').before(yishouqing); //添加 class="off-sale" 出现下架 var yixiajia = '<div class="off"><!--已下架-->\ <i class="icon icon-yixiajia"><!--已下架--></i>\ </div>'; $('.off-sale').before(yixiajia); Vue.component('GoodsComments', require('./components/goods/GoodsComments.vue')); /*const app = new Vue({ el: '#app', });*/
//crystals var crystal = ["blue", "red", "green", "orange"]; //variables var yourScore = 0; var number = 0; var win = 0; var lose = 0; //random number function var randomNumber = function (min, max) { return Math.floor((Math.random() * max - min + 1) + min); }; var game = function () { yourScore = 0; //get random number for the random score number = randomNumber(19, 120); console.log(number); $("#randomNumber").html(number); $("#userScore").html(yourScore); for (var i = 0; i < 4; i++) { $(".image-" + i).attr("data-crystalvalue", randomNumber(1, 9)); } }; //get random number for each crystal // crystal.blue.value = randomNumber(1, 100); // crystal.red.value = randomNumber(1, 100); // crystal.green.value = randomNumber(1, 100); // crystal.orange.value = randomNumber(1, 100); // console.log("blue:" + crystal.blue.value); // console.log("red:" + crystal.red.value); // console.log("green:" + crystal.green.value); // console.log("orange:" + crystal.orange.value); //function to add the value of the crystals to the random number var crystalValue = function (crystal) { yourScore = yourScore + Number(crystal); $("#yourScore").html(yourScore); checkWins(); } var checkWins = function () { // var lose = 0; if (yourScore > number) { alert("you lost"); console.log("you lost"); lose++; $("#losses").html(lose); //restart game game(); } else if (yourScore === number) { // var win = 0; alert("you won"); console.log("you won"); win++; $("#wins").html(win); //restart game game(); } }; //reinitialize game game(); //on-click for the crystal images $("#blue").on("click", function () { crystalValue($(this).attr("data-crystalvalue")); console.log($(this).attr("data-crystalvalue")); }); $("#red").on("click", function () { crystalValue($(this).attr("data-crystalvalue")); console.log($(this).attr("data-crystalvalue")); }); $("#green").on("click", function () { crystalValue($(this).attr("data-crystalvalue")); console.log($(this).attr("data-crystalvalue")); }); $("#orange").on("click", function () { crystalValue($(this).attr("data-crystalvalue")); console.log($(this).attr("data-crystalvalue")); });
const getters = { username: state => state.login.username, role: state => state.login.role, newrouter: state => state.login.newrouter, node: state => state.login.node, hospitalId: state => state.login.hospitalId, hospitalname: state => state.login.hospitalname, phone: state => state.login.phone, password: state => state.login.password }; export default getters
let a = 5; let b = 3; console.log(a + b);
import { timestampFromDateString } from "./utils/date"; import { getAllSubRedditPostsNewerThan } from "./utils/reddit"; const getUniqueDomainsFromSubRedditPosts = async (subReddit, dateString) => { const timestamp = timestampFromDateString(dateString); const posts = await getAllSubRedditPostsNewerThan(subReddit, timestamp); const uniqueDomains = [...new Set(posts.map(post => post.domain))]; return uniqueDomains; }; export default getUniqueDomainsFromSubRedditPosts;
import React from 'react' import Preloader from 'components/Preloader/Preloader' import Events from 'components/Events.jsx' function Event() { return ( <div> <Preloader/> <Events/> </div> ); } export default Event
import React, {Component} from 'react' import firebase from 'firebase' //estilos import './Dash.css' //components import Pin from './Pin/' class Dash extends Component{ constructor(props){ super(props) this.state = { tasks: [], proceso: [], retraso: [], listo: [], date: new Date, dia: null, hora: null, minutos: null, segundos: null, tiempo: null } this.dbTask = firebase.database().ref(`users/${this.props.userId}/tasks`) this.dbProceso = firebase.database().ref(`users/${this.props.userId}/proceso`) this.dbRetraso = firebase.database().ref(`users/${this.props.userId}/retraso`) this.dbListo = firebase.database().ref(`users/${this.props.userId}/listo`) this.reloj = this.reloj.bind(this) this.removeTask = this.removeTask.bind(this) this.removeProceso = this.removeProceso.bind(this) this.removeRetraso = this.removeRetraso.bind(this) this.removeListo = this.removeListo.bind(this) this.handleProceso = this.handleProceso.bind(this) } componentDidMount(){ this.reloj() } handleProceso(proceso){ this.dbProceso.push().set({ tarea: proceso.taskContent, inicio: proceso.inicio, final: proceso.final, dia: proceso.dia }) alert('Tienes una tarea en proceso') } handleListo(listo){ this.dbListo.push().set({ tarea: listo.taskContent, inicio: listo.inicio, final: listo.final, dia: listo.dia }) alert('Tienes una tarea terminada') } reloj(){ setInterval(()=>{ let date = new Date let minutos = this.state.date.getMinutes() if(minutos < 10){ minutos = `0${minutos}` } this.setState({ date, dia: this.state.date.getUTCDate(), hora: this.state.date.getHours(), minutos: minutos, segundos: this.state.date.getSeconds(), tiempo: `${this.state.hora}:${this.state.minutos}:${this.state.segundos}` }) for(let i = 0; i < this.state.tasks.length; i++){ if(this.state.tasks[i].inicio <= this.state.tiempo){ this.handleProceso(this.state.tasks[i]) this.removeTask(this.state.tasks[i].taskId) } } for(let i = 0; i < this.state.proceso.length; i++){ if(this.state.proceso[i].final <= this.state.tiempo){ this.handleListo(this.state.proceso[i]) this.removeProceso(this.state.proceso[i].taskId) } } for(let i = 0; i < this.state.listo.length; i++){ console.log(this.state.listo[i].dia) if(this.state.listo[i].dia < this.state.dia){ this.removeListo(this.state.listo[i].taskId) } } }, 1000) } removeTask(taskId){ this.dbTask.child(taskId).remove(); } removeProceso(taskId){ console.log(taskId) console.log(this.dbProceso) this.dbProceso.child(taskId).remove(); } removeRetraso(taskId){ this.dbRetraso.child(taskId).remove(); } removeListo(taskId){ this.dbListo.child(taskId).remove(); } render(){ return( <section className="Dash"> <Pin title="Tareas" tasks={this.state.tasks} remove={this.removeTask} db={this.dbTask} /> <Pin title="En proceso" tasks={this.state.proceso} remove={this.removeProceso} db={this.dbProceso} /> <Pin title="Retraso" tasks={this.state.retraso} remove={this.removeRetraso} db={this.dbRetraso} /> <Pin title="Listo" tasks={this.state.listo} remove={this.removeListo} db={this.dbListo} /> </section> ) } } export default Dash;
/* TestFlight Plugin for Apache Cordova. Created by Shazron Abdullah 1. Include the TestFlight SDK files in Xcode (follow their instructions) 2. Add CDVTestFlight.h and .m in Xcode 3. Add testflight.js to your www folder, and reference it in a script tag after your cordova.js 4. In Cordova.plist, under the 'Plugins' key, add a new row: key is "TestFlightSDK" and the value is "CDVTestFlight" 5. In Cordova.plist, under the 'ExternalHosts' key, add a new value "testflightapp.com" The plugin's JavaScript functions are called after getting the plugin object thus: var tf = cordova.require("cordova/plugin/testflightsdk"); tf.takeoff(win, fail, "some_team_token"); See the functions below (and the TestFlight SDK docs) for usage. Unfortunately all of TestFlight's SDK functions return void, and errors can only be gleaned from the run console, so check that for errors. */ cordova.define("cordova/plugin/testflightsdk", function(require, exports, module) { var exec = require('cordova/exec'); var TestFlight = function() { this.serviceName = "TestFlightSDK"; }; /* Add custom environment information If you want to track a user name from your application you can add it here @param successCallback function @param failureCallback function @param key string @param information string */ TestFlight.prototype.addCustomEnvironmentInformation = function(successCallback, failureCallback, key, information) { exec(successCallback, failureCallback, this.serviceName, "addCustomEnvironmentInformation", [ key, information]); }; /* Starts a TestFlight session @param successCallback function @param failureCallback function @param teamToken string */ TestFlight.prototype.takeOff = function(successCallback, failureCallback, teamToken) { exec(successCallback, failureCallback, this.serviceName, "takeOff", [ teamToken ]); }; /* Sets custom options @param successCallback function @param failureCallback function @param options object i.e { reinstallCrashHandlers : true } */ TestFlight.prototype.setOptions = function(successCallback, failureCallback, options) { if (!(null !== options && 'object' == typeof(options))) { options = {}; } exec(successCallback, failureCallback, this.serviceName, "setOptions", [ options ]); }; /* Track when a user has passed a checkpoint after the flight has taken off. Eg. passed level 1, posted high score @param successCallback function @param failureCallback function @param checkpointName string */ TestFlight.prototype.passCheckpoint = function(successCallback, failureCallback, checkpointName) { exec(successCallback, failureCallback, this.serviceName, "passCheckpoint", [ checkpointName ]); }; /* Remote logging @param successCallback function @param failureCallback function @param message string */ TestFlight.prototype.remoteLog = function(successCallback, failureCallback, message) { exec(successCallback, failureCallback, this.serviceName, "remoteLog", [ message ]); }; /* Opens a feedback window that is not attached to a checkpoint @param successCallback function @param failureCallback function */ TestFlight.prototype.openFeedbackView = function(successCallback, failureCallback) { exec(successCallback, failureCallback, this.serviceName, "openFeedbackView", []); }; /* Submits custom feedback to the site. Sends the data in feedback to the site. This is to be used as the method to submit feedback from custom feedback forms. @param feedback Your users feedback, method does nothing if feedback is nil */ TestFlight.prototype.submitFeedback = function(successCallback, failureCallback, feedback) { exec(successCallback, failureCallback, this.serviceName, "submitFeedback", [ feedback ]); }; /* Sets the Device Identifier. The SDK no longer obtains the device unique identifier. This method should only be used during testing so that you can identify a testers test data with them. If you do not provide the identifier you will still see all session data, with checkpoints and logs, but the data will be anonymized. @param deviceIdentifer The current devices device identifier */ TestFlight.prototype.setDeviceIdentifier = function(successCallback, failureCallback, deviceIdentifier) { exec(successCallback, failureCallback, this.serviceName, "setDeviceIdentifier", [ deviceIdentifier ]); }; /* If app is compiled on DEBUG, sets the Device Identifier from actual UUID. Otherwise, does nothing */ TestFlight.prototype.setDeviceIdentifierUUID = function(successCallback, failureCallback) { exec(successCallback, failureCallback, this.serviceName, "setDeviceIdentifierUUID", [ ]); }; var testflight = new TestFlight(); module.exports = testflight; });
export const initState = { loading: false, users: [], error: '', }; export const FETCH_USERS_REQUEST = 'FETCH_USERS_REQUEST'; export const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS'; export const FETCH_USERS_FAILURE = 'FETCH_USERS_FAILURE'; export const fetchUsersRequest = () => { return { type: FETCH_USERS_REQUEST, }; }; const fetchUsersSuccess = (users) => { return { type: FETCH_USERS_SUCCESS, payload: users, }; }; const fetchUsersFailure = (error) => { return { type: FETCH_USERS_FAILURE, payload: error, }; };