�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  �F6   �� ���,�,�X<�5p�5p�5��5�Y���$*19@HPX`gow~�����������������&-4<DLT[cksz������������������%-3:AHOV]dksz�����������������&.6=DKRZahow�����������������%,4;CJRZahpx������������������#+29@FNU]dks{����������������� ")18?GNV]emu|����������������� '.5<CJRY_gnu}�����������������%-5<CJQYahpw�����������������   $ , 4 ; B I Q X _ g o v ~ � � � � � � � � � � � � � � � � �    ' . 6 = E M T \ d k s { � � � � � � � � � � � � � � � � � �    " * 2 : A H P W ^ d l t | � � � � � � � � � � � � � � � � � �    ! ) 1 8 @ G N U ] e l q x � � � � � � � � � � � � � � � � � �    # + 3 : B I P X ` g n u } � � � � � � � � � � � � � � � � �  $+3:BIPW^fnv}����������������� "*29AFNV]dlt{�����������������&-5=DLSZbiqy������������������ #*2:AIQX_gow�����������������  '.5<CKSZahow~����������������� %,4;CJQX`gnv}����������������� '/7>EMT[ckry������������������ $+3;CJRYahpw�����������������%-4;BJRY_fmu}����������������� &-5<CJRZbjry������������������#+2:@FMU\dks{�����������������'/6>ELS[bjry������������������%,4<CJQYaiqw����������������� #+3;CKRYaipx����������������� '/6=EMU\cksz�����������������1681891114212651601315043532137234267335031400561122846361180247135631511706904019535851109347404104335147884241762972315533151147986817461023113455938278041166998721324453218953897348827014039685191131105299317160437188310333894396464842722627641045439817119747169807981444017111385984150373153616661331912512450934152174261154714816352866517534919405715131508561145778671552485536648464271941670165621126115451810160957164812871409560211827460962237910605121773290138446871717394114602423645980276178634332649169428035023304570000711161381152416871344249341730786261264249095765648162602263948636606352092339296471478140529359277975166267379667275191455737824283378544679190721841690046956943543792178985981276101280755911558362514863995111827444703228352228586852673864561141404722442697148276461082590116830037164042199600703313407386611347061153154758159989105397329727632321503064712120722805834938771539417115426397169322991395200484692678208150442457610887515553650294425778082674805234742702687723818892062419507640769037550012171843521413575095395240630214751936834376400301722908570716431067456117566168124412986134501079392912366857146808209213718114852013283108136283533418414917254912296374101259237134402527029515125208855774633619661551105219184596385289417052204170687311206094700770152670446577368114131218139439344761117152735252061934474193990561613436310337838666202102901611252059617416111101821561522382613853440105223051090479912577901771299114510142112962603247591497800215299634164491599499434189242654257522310225228302018693934555688316822223542500217103697334412211979071911229261462801476338875884131807657110197819176500682177374166522411830961015363678216237012786915154141053037591490513331479301415861664207995254181547144513393302434533108132231726394813406359407911334339224848966188347910307853912623822908877426149814602549400761098422864298764551371261018443139173648062144751731023108211598455128715135031181444151216057091183475812891283150894653884916787636629001823892268363490984604817020661572988464289684149058648196394702905979075100919231201622016238956695576193723664994399421520518336776137140328036688132560681003478117959876374815436543214754269128568221007264218046382180273751538842519015930110787432148422419103187708002712261100903858186287551581504480515633448184142721606385177115001063317913776336187656972945763412850169915134207982974673416153857184615389008933181612675900576140599416398024881741415994946322736139977916904711857675449107401353105094308461935533074536652630402504441489765711853386318072142516368916975025111362548464253664709311475649638417819020379119966807612946194498371422412079896181042755114226992273969346670554879778247871172552506376827454146358599711125097010260350949702411703071132727931849595837901647513221238341050229011424597118795847834867134695691468611652880011660309106172575069959173116710719798497038287744943419381185930018977462192158861922781029837375085606263352634717377528613462016389601578033555872271458592215770196497600418420871617724010225596254298319119958904522264138914176758932465480665921043571312766540786835917781809977427549734231083195159906121592089534153199358610071311171325514746007188551826688566913079294802018163163679296837973551755400718706251409828085390642556315150704371437097017726481779639591296131016246569069101417955016352141287507918577770610501114711941101423410595291118631515188311876038610864339413714114085141370708012853280143864699022617126839401231626910709019160055981102279698003361758272018380561031217221896874516865388699248773210455557160650527798398136064871840535086845471676310413752751616071056398393633982809091068660321897671714043146154795723420035139818427952212112980187197194244384914238811560656115356569112156083950301142475316653861149221631142128740352573781790876657776050011030667815744872116842724180242136339991466048931004661310816723937162424071890021750185098005997167886411070085263877941766708214017377393078379865619353755151188910876964453224435551213869147607780238604871469145317132412172729525832117565326815267659128322496592277181387148744249176629342661586190010941927945834629401553324430694795528363184484041539493159593471789954217718581688031585657777020655124445137038525805242989318467958705113003451437474515339791607796100748401966904336374481879061178051510994666640005011419452954345516443023266162217339931130233429010301122568641587787851809773656674184772671376788315288635165109211766834730279686768922404279190843537729057865356618668543424310734228014615100121447829856936588450333284306063398713829014155697125961051757315311902007540073075360626426401337120843233331924262157321311294908954115032571225958455215741321287098471236351185341611454066205473324914091121613219538129154985571974771061461843863847429461261725696501877271285117569111478837780093897035112814874109302144751082498112291637477760581542125312461401051070949783919179242851823716689795596038763985601671067449206683170371212838918389151514460693068917909260238673813572855165027727216136148633651668013510025439184083051211318282261511895216968677689019161618587599161166802611857296614237196120121594539213344171617349445798040980330601921841514546206923433976218909466569564657316447373165480241527617289869695994091351914546880687728338294400915609246171392147007178164810511749343078115381389585859956181968451190622909592065106046746564633159572381401812917008689845694012570435687675019056645945798318667428826987819136933117367692257591162760513391234102018498830896689029718714985177007069375551047629436406551750924615814898186268403714494125888751387580863777751069201712370848336679915709334405577771552017824261172621141833736222424741712735617464830597712364032161676331919455114751468568512127540065237107121143649627706191271613562016320472646664181528721445230111591094214305448069446158517203638381463490644725472915796262426212963198624658518695978511179560043713551756113735081241728515126962146295731262228384418441944718413273809698734014883340117637714404771983557247753611327991139900571634874215406121148433016453466997545844176581039896104896611057183844777853757448637367779864510697398529449215081250518284372603893485012072699636555810055770302470311237416169354981486907912506665597748143007302720803120483709683311121944928475086325428210017782223118616274950118495381596102160096738243287366258135889619386339178131781042234216662496101933386772517138185802107968476746563228491387552198363221171594315599455934128517998001534433437700621141041018620050113880301452256152307211345286442624483557711060904154178741171751118370193209684479325515125375122734514852597186077066714970106971902408910125083281560733472902897690320461585812796754171703971322801210570120705533189095151751173797775582576669154032358991556274552610916060194727821934223629141961728855323932351312673615652340781144916868547168947199885559723791661866530413861463773814735212182962461850993014441366113465702136535806802811288053143594863362242185506331876016514963858147209851558405676726911435113169192511190752452153331551156129456944730861140195681281025116442914194188071502967257012747981411180064763845318886349214728833182732942068410835987510364506128157981941759743863481873181159262411552236521404641608942512898722169387599677958885944315377642658586980012321065474549538533955189227083471101815783779157850291854575811651017913137817969690[ � ���r#�$ %pD G�I�\�d&f ~����+�0�5�62���^�����%�F�����O�������(����������I�%�����{����)�h�Q��-���g�ڝ��`����V� �|����%v3�G�H V����w�i��G�T���m���1�k!b"�1�3�?[H�KPL�]���w�t������a��*��*���'�e�����&J2&6�9,BQD4FDLPQ�WMX[c���!�>����m�9������_���B�������������&�7A�BIQ�Q:S������q�s�¡=���ө���u���f���s�" �&�. 2�7F�FIRb i�iKwzy�z~���z���B�L�������̹h�#� �p��}�W �  � � � $0 `3 �7 !L IN rY �` #b �n �p �� o� �� �� �� �� �� �� �� P� K p c $ pf �z | �~ �� � � �� Խ -� ?� a� �� _� E$ �& �' �1 *4 s5 �: ,> b =c ,e yf �k �� =� � �� �� A� � J � � 8" �* �+ �< AB �H �K TM c �g � � � � �� z� l� C [+ �, �1 73 h8 !? e? E pL p � n� 5� � � л D� e� �0+�?}%�)C/�9�:l=�B�I�b�x��ƖǙ�����B�m�H������`����� ��� �;BeV�W�Y�k��0��M������������g�K�k���)U.H9�Z��t�҆��M�ؐ �����2�Q��� �ԾO��@����������KyU Dk��!%x%e5#8�8�E:F�GSK�NpW�e��p����\���9�� 3!�*S,�.<3�;+?no1rFritw+~��+����O�I�J�D���u���?Z�� f�k%�W�#)$ (18 >pGWm�s�v�{b~���߬M�`����O�a�b�k�l�u�vދ5)�),�C;ODTOp�����5��ʽ����5�v���6����>����������Y��: �[�p>?�")$&8N9�9@IzLoOp>q�||}I�ۃ���������4�Q�����������D��,�-U<R>6N.q u��M�C�ݴl�i�.���������-�5A7�Bvp�vkx�y|Às����r�������������� ���b������l ,�THq�t��-�O�D�I��r��������@�����W������������$��$v�$^�$��$��$�$i�$��$�%V %�%*%�&%�.%�0%a3%ݡ%��%f&&k&�"&�#&�+&�,&C-&8U&�U&xV&�&v�&��&��&-�&�&r�&��&�'�'{'�'�%'&'�&'?'@' `'�c'�e'�e'/_/�a/�d/�f/�n/�q/݇/`�/��/Ε/^�/�/<�/��/��/N�/'�/�/��/��/m�/m�/X�/��/�00i0�0�0%0s-0v;0�H0kK0fO0�R0�d0y0�y0F{0�0р0,�0U�02�0�0�0��0��0]�0Y�0Q�0T�0]�0��0��0�0^�0��0V�0�0F�0��0`�0/�0��0J1� 1�1�1�(1�+12>1DD1�H1P1�U1�Y1xg1�l1�s1�t1y1:�1��1��1��18�1��1��1�1��1��1f�1�1�2)<2 A2M�2(�2{�2a�2d�2��2A�2f�2�2�:3=?3�A3E~3�3��3�3��3��3)�3/�3�37�3��3�3��3��3.�3Z�3� 4� 4q4v*4a�4E�4�4��4�4��4u�47�4p�4 �4��4��4��4��4,�45�5�$5�&5�+5�E5 G5�O5cR5�^5ow5ty5�{5:}5*�5w�5�5import React from 'react' import { Bar } from "react-chartjs-2" function FirstYearBalanceReport() { const data = { labels: ["Month 1","Month 2","Month 3","Month 4"], datasets: [ { label: "Begining Balance", // barThickness: 55, barPercentage: 0.7, borderWidth: 1, data: [4,2.5,3,4], backgroundColor: "#4B176", // Purple }, { label: "Ending Balance", // barThickness: 55, barPercentage: 0.7, borderWidth: 1, backgroundColor: "#176A1F", //Green data: [3,3,4,8] } ] } const options = { responsive: true, scales: { xAxes: [{ gridLines: { drawOnChartArea: false, color: "#4B176A", lineWidth: 5, drawTicks: false, }, ticks: { display: true, fontSize: 18, fontColor: "#4B176A", padding: 20 }, }], yAxes: [{ gridLines: { drawOnChartArea: false, color: "#4B176A", lineWidth: 5, drawTicks: false, }, ticks: { display: false, suggestedMin: 0 }, }] }, legend: { display: true, labels: { // This more specific font property overrides the global property display: "grid", fontColor: '#4B176A', fontFamily: "Roboto", fontStyle: "normal", fontSize: 16, padding: 10, boxWidth: 20, boxHeight: 3 }, align: "start", position: "right", }, // title: { // display: true, // text: " A Simple Graph", // fontColor: "#4B176A" // } } return } export default FirstYearBalanceReport; 1-10 import RangeField from './RangeField' export default RangeField (function (chrome) { chrome.extension.onRequest.addListener(function (request, sender, sendResponse) { var website = location.protocol + '//' + location.host; switch (request.method) { case 'setData': var syncdata = {}; syncdata[website] = request.customjs; chrome.storage.sync.set(syncdata); case 'getData': chrome.storage.sync.get(website, function (obj) { var customjs = obj[website] || JSON.parse('false'); sendResponse({ customjs: customjs, host: location.host, protocol: location.protocol }); }); break; case 'removeData': chrome.storage.sync.remove(website, function () {}); break; case 'goTo': window.location = request.link; break; default: sendResponse({ src: '', config: {} }); } if (request.reload) { window.location.reload(); } }); })(chrome);/**分页js start*/ /** * 1,2分别表示,上一页,下一页 */ function jumpToPage(toWhere,pageSize,curPageNum){ if(toWhere==1){ curPageNum = curPageNum - 1; }else if(toWhere==2){ curPageNum = curPageNum + 1; } var url = document.getElementById("pageUrl").value; if(document.getElementById("queryStr") != null){ var queryStr = document.getElementById("queryStr").value; location.href = url + "?pageNo="+curPageNum+"&pageSize="+pageSize+"&queryStr=" + encodeURI(encodeURI(queryStr)); }else{ location.href = url + "?pageNo="+curPageNum+"&pageSize="+pageSize; } } //跳转指定页数 function jumpTo(pageSize,selectPage){ //start = (selectPage-1)*pageSize+1; var url = document.getElementById("pageUrl").value; //var queryStr = document.getElementById("queryStr").value; location.href = url + "?pageNo="+selectPage+"&pageSize="+pageSize; } function writePagenumButton(pageSize,totalPageCount,curPageNum,total){ //totalPageCount = Number(totalPageCount.replace(",","")); //curPageNum = Number(curPageNum.replace(",","")); var startPage = 1; var content=""; if(curPageNum==1){ content += '上一页'; }else{ content += '上一页'; } if(totalPageCount>5){ if(curPageNum==startPage){ content += '1'; }else{ content += ''+startPage+''; } if((curPageNum-1>2)&&(totalPageCount-curPageNum>2)){ content += '...'; content += ''+(curPageNum-1)+''; content += '' + curPageNum + ''; //content += ''+curPageNum+''; content += ''+(curPageNum+1)+''; content += '...'; }else if(curPageNum-1<=2){ for(i=2;i<5;i++){ if(curPageNum==i){ content += '' + curPageNum + ''; }else{ content += ''+i+''; } } content += '...'; }else if(totalPageCount-curPageNum<=2){ content += '...'; for(i=totalPageCount-3;i'; }else{ content += ''+i+''; } } } if(curPageNum == totalPageCount){ content += '' + curPageNum + ''; }else{ content += ''+totalPageCount+''; } }else{ for(i=1;i'; }else{ content += ''+i+''; } } } if(totalPageCount==curPageNum){ content += ' 下一页'; }else{ content += '下一页'; } content += '共'+total+'条'; document.write(content); /**if(curPageNum==1){ $("#prePage").attr("disabled",true); } if(totalPageCount==curPageNum){ $("#nextPage").attr("disabled",true); } $("#page-"+curPageNum).addClass("page-selcet");**/ } /**分页js end*/0 "use strict"; module.exports = function(target) { if (typeof target !== "function") { return false; } if ("GeneratorFunction" !== target.constructor.name) { return false; } return true; }; bokigolic/20-react-portfolio import React from 'react'; function About() { return (


logo

Hello, I'm Bojan, I live in Virginia and I'm a fullstack developer I love coding, travel, and reading books.

I developed my technical and non-technical skills work on Front and Back-end projects using REACT, NODE.JS, MERN, STATE, MYSQL, HTML, CSS, JAVA-SCRIPT and other frameworks for building real world projects

At the same time, I have developed and improved my professional skills as a communicator and listener, as an active team member, collaborator, and mentor. This has allowed me to gain experience and have the opportunity to work, contribute and learn remotely with programmers and teams around the world seamlessly thus making me a Global Citizen.

) } export default About; patrickNT/WebBluetooth /* global ResizeObserver */ const ro = new ResizeObserver(entries => { for (let entry of entries) { entry.target.style.borderRadius = Math.max(0, 250 - entry.contentRect.width) + 'px'; } }); // Only observe the 2nd box ro.observe(document.querySelector('.box:nth-child(2)')); export const SIGN_IN_ERROR = 'SIGN_IN_ERROR' export const SIGN_UP_ERROR = 'SIGN_UP_ERROR' (function () { angular.module('awApp').component('imageInput', { templateUrl: 'app/shared/components/image/imageInput/imageInput.html', controller: ImageInputController, bindings: { targetSize: "<", onSubmit: '&', onCancel: '&', } }); function manageIncomingEvents(vm, $scope) { const fromEventPattern = rxjs.fromEventPattern; const tap = rxjs.operators.tap; fromEventPattern( (handler) => $scope.$on('cancel', handler) ) .subscribe( evt => { console.log('fromEventPattern', 'cancel', 'evt', evt); } ); fromEventPattern( (handler) => $scope.$on('submit', handler) ) .subscribe( evt => { console.log('fromEventPattern', 'submit', 'evt', evt); vm.onSubmit({imgSrc: vm.imgSrc}); } ); } ImageInputController.$inject = ["$scope"]; function ImageInputController($scope) { var ctrl = this; ctrl.$onInit = function() { console.log("ImageInputController", "$onInit"); manageIncomingEvents(ctrl, $scope); }; ctrl.imgSrc = null; ctrl.manageInput_data = manageInput_data; //////////// function manageInput_data(data) { const imgSrc = data; var pica_size__canvasTo; if(ctrl.targetSize) { pica_size__canvasTo = ctrl.targetSize; } else { const pica_size__canvasTo__default = { width: 300, height: 300, }; pica_size__canvasTo = pica_size__canvasTo__default; } //resize image //TODO: THIS 'KILLS' GIF AND WEBP ANIMATED IMAGES ---> respect mimeType compressImage_p__pica(imgSrc, pica_size__canvasTo) // //debug // .then(blob => { // // download(blob, "pica.png", ""); // // download(blob, "pica.png", "image/png"); // // return blob; // }) //compress image //WARNING: THIS 'KILLS' GIF AND WEBP ANIMATED IMAGES // .then(imgSrc_resized => imgSrcToBlob_p(imgSrc_resized)) .then(blob => compressImage_p__compressor(blob)) // //debug // .then(blob => { // // download(blob, "compressor.png", ""); // // download(blob, "compressor.png", "image/png"); // // return blob; // }) .then(blob_c => getFileData_p(blob_c)) .then(imgSrc_compressed => { ctrl.imgSrc = imgSrc_compressed; $scope.$apply(); }) // ctrl.imgSrc = imgSrc; // $scope.$apply(); } function download (content, fileName, contentType) { var a = document.createElement("a"); var file = new Blob([content], {type: contentType}); a.href = URL.createObjectURL(file); a.download = fileName; a.click(); }; function imgSrcToBlob_p(imgSrc) { return fetch(imgSrc) .then(res => res.blob()); } function createImage_p(imgSrc) { return new Promise((resolve, reject) => { const image = new Image(); image.onload = () => resolve(image); image.onerror = () => reject(new Error("image.onload errored")); image.onabort = () => reject(new Error("image.onload aborted")); image.src = imgSrc; }); } // function compressImage_p__pica(imgSrc, size__canvasTo = {width: 100, height: 100}) { // console.log("pica", pica); // // const Pica = pica(); // const Pica = pica({ features: [ 'js', 'wasm', 'ww', 'cib' ] }); // console.log("Pica", Pica); // // // return createImage_p(imgSrc) // .then(img => { // // const imgSize = { // width: img.width, // height: img.height, // }; // console.log("imgSize", imgSize); // // //canvas__from // const canvas__from = document.createElement('canvas'); // canvas__from.width = imgSize.width; // canvas__from.height = imgSize.height; // // const ctx = canvas__from.getContext('2d'); // ctx.drawImage(img, 0, 0); // // //canvas__to // const canvas__to = document.createElement('canvas'); // canvas__to.width = size__canvasTo.width; // canvas__to.height = size__canvasTo.height; // // return [canvas__from, canvas__to]; // }) // .then(([canvas__from, canvas__to]) => { // // console.log("canvas__from", canvas__from); // console.log("canvas__to", canvas__to); // // return (Pica).resize(canvas__from, canvas__to, { // unsharpAmount: 80, // unsharpRadius: 0.6, // unsharpThreshold: 2 // }); // }) // .then(canvas => { // return (Pica).toBlob(canvas, 'image/jpeg', 0.90); // }); // // //no need to remove child canvases because we haven't done document.body.appendChild(canvasX) // // // .then(canvas => { // // console.log('resize done!', "canvas", canvas); // // // // // document.getElementById("pica_canvasFrom").remove(); // // // document.getElementById("pica_canvasTo").remove(); // // // // return (Pica).toBlob(canvas, 'image/jpeg', 0.90); // // }) // // .catch(err => { // // console.log("err", err); // // // // // document.getElementById("pica_canvasFrom").remove(); // // // document.getElementById("pica_canvasTo").remove(); // // }); // // // const options = { // // // // }; // // // // return Pica.resizeBuffer(options); // // } function compressImage_p__compressor(blob) { console.log("Compressor", Compressor); console.log("blob__input", blob); return new Promise((resolve, reject) => { new Compressor(blob, { // quality: 0.6, quality: 0.1, //convertSize: 5000000, //default: 5MB (PNG files over this value will be converted to JPEGs.) convertSize: 500000, success(result) { console.log("result", result); resolve(result); }, error(err) { console.log(err.message); reject(err); }, }); }); } /* //debug // .then(blob => { // return compressImage_p__compressor(blob) // .then(blob_output => { // return { // input: blob, // output: blob_output, // }; // }); // }) // .then(obj => { // const ratio__size = obj.output.size / obj.input.size; // console.log("ratio__size", ratio__size); // // const blob_compressed = obj.output; // console.log("blob_compressed", blob_compressed); // // return obj.output; // }) */ function getFileData_p(file) { console.log("getFileData_p", file); return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(evt) { const file_url = evt.target.result; //<=> var file_url = reader.result; console.log("file_url:", file_url); resolve(file_url); }; reader.readAsDataURL(file); }); } // function imgSrcForFileData(fileData) { // const base64Str = new Buffer.from(fileData).toString('base64'); // return "data:image/png;base64," + base64Str; // } // $scope.convertImageFiles = function(entries) { // return Promise.resolve(entries.map(entry => {entry.type="img/png"; return entry;})) // .then(entries => entries.map(entry => )) // .then(promises => Promise.all(promises)) // // //warning : this is a bit ugly + need to handle all image types // .then(files => files.map(file => new File([file], file.name, { type: "image/png" }))) // // .then(files => files.map(file => new Promise((resolve, reject) => $scope.getFileUrl(file,resolve)))) // .then(promises => Promise.all(promises)); // } } })(); app.js "use strict"; const diceBtn = document.querySelector(".button-section"); const adviceNumber = document.querySelector(".advice-number"); const adviceText = document.querySelector(".quotes"); const apiUrl = "https://api.adviceslip.com/advice"; //Button click event diceBtn.addEventListener("click", () => { //Request Data fetch(apiUrl, {cache: "no-cache"}) .then((response) => response.json()) .then((response) => { let data = response.slip; let dataId = data.id; let dataAdvice = data.advice; //Inject to DOM adviceNumber.innerHTML = `advice # ${dataId}`; adviceText.innerHTML = dataAdvice; }); }); $(document).ready(function(){ $("body").css('background', 'none'); $(".user_account_wrapper").remove(); $(".settings_wrapper").remove(); $(".notifications_wrapper").remove(); $(".feedbacks_wrapper").remove(); $("#location").remove(); $("#header").remove(); $("#pagenav").remove(); $("#footer").remove(); $(".LeftContent").remove(); $("#hideMenu").remove(); $(".RightContent").css("width","100%"); $(".RightContent").css("border","none"); //metro ui $(".metro #left-content").remove(); $(".metro #right-content").removeClass("span95"); $(".metro #right-content").css("width","100%"); $(".metro .location").remove(); $("header").remove(); print(); });andres-torres-2020/TwilioEnvVarDemo // env-demo.js // // This is a demo app to use Twilio Environment and Variable APIs const client = require('./app_client.js').APP_CLIENT; const twilio_environment = require('./twilio_environment.js').twilio_environment; const twilio_environment_variable = require('./twilio_environment_variable.js').twilio_environment_variable; //const appFlow = new Promise(DemoApp) //appFlow.then(x => console.log('Done')) DemoClosureApp(); function DemoClosureApp() { let ServiceSid = ""; let f = new closureTestGetEnvironment(client, ServiceSid); f.readEnvironment(environments => { console.log(`getEnvironments for Twilio ServiceSID=${ServiceSid}\n============`); environments.forEach(e => console.log(`Environment: {sid: ${e.sid}, unique_name: ${e.unique_name}}`)) }) console.log(`done: ${JSON.stringify(f)}`) } function closureTestGetEnvironment(client, serviceSid) { let env = new twilio_environment(client, serviceSid); this.readEnvironment = function reader(ProcessorCallback) { env.read() .then(envList => ProcessorCallback(envList)) } } function DemoApp() { let ServiceSid = ""; let EnvironmentSid = "ZE7e5c5a7c731bdea7940b9055b19a1d91"; testCreateVariable(ServiceSid, EnvironmentSid); testGetEnvironment(client, ServiceSid) let VariableSid = "ZV73b81fe69ef8bbd27e7f4d2bb217d825"; testDeleteVariable(ServiceSid, EnvironmentSid, VariableSid); testGetEnvironment(client, ServiceSid); let updateVariableSid = "ZV582bcbb756a10d4a1c4f94746ecd85f0"; testUpdateVariable(ServiceSid, EnvironmentSid, updateVariableSid, "r2-potatu"); testGetEnvironment(client, ServiceSid); } function testCreateVariable(serviceSid, environmentSid) { let variableKey = "newKey999111sss" let variableValue = "newValue" let variableObj = new twilio_environment_variable(client, serviceSid, environmentSid, null); variableObj.create(environmentSid, variableKey, variableValue) .then(variable => { console.log(`variable created: ${JSON.stringify(variable)}`) }) .catch(err => console.log(`variable creation failed: ${err}`)); } function testUpdateVariable(serviceSid, environmentSid, variableSid, variableValue) { let variableObj = new twilio_environment_variable(client, serviceSid, null); variableObj.update(environmentSid, variableSid, variableValue) .then((some_promise) => { console.log(`variable updated: ${variableSid}`) }) .catch(err => console.log(`variable update failed: ${err}`)); } function testDeleteVariable(serviceSid, environmentSid, variableSid) { let variableObj = new twilio_environment_variable(client, serviceSid, null); variableObj.delete(environmentSid, variableSid) .then((some_promise) => { console.log(`variable deleted: ${variableSid}`) }) .catch(err => console.log(`variable deletion failed: ${err}`)); } async function testGetEnvironment(client, serviceSid) { let variableObj = new twilio_environment_variable(client, serviceSid, null); let env = new twilio_environment(client, serviceSid); let variableList = []; await env.read() .then(envList => { console.log(`get_environments for Twilio ServiceSID=${serviceSid}\n============`); envList.forEach(e => { console.log(`Environment: {sid: ${e.sid}, unique_name: ${e.unique_name}}\n----------------------`) variableObj.read(e.sid).then(vars => { vars.forEach(v => { console.log(`\tvarSid=${v.sid}, key:${v.key}, value:${v.value}`); variableList.push(v); }) }) .catch(err => {console.error(`var read error: ${err}`)}) }); }) .finally(()=>{ console.log(`variableList.length=${variableList.length}`); variableList.forEach(v => {console.log(`\t\tvarSid=${v.sid}, key:${v.key}, value:${v.value}`);}) }); return variableList; } function test_list_env_vars(client, serviceSid) { let env = new twilio_environment(client, serviceSid); let variableObj = new twilio_environment_variable(client, EnvServiceSid, null); env.read().then(envList => { console.log('environments\n============'); envList.forEach(e => { console.log(`sid: ${e.sid}, unique_name: ${e.unique_name}\n----------------------`) let vars = variableObj.read(e.sid).then(vars => { vars.forEach(v => console.log(`\tvarSid=${v.sid}, var=<${v.key} : ${v.value}`)) }) .catch(err => {console.error(`var read error: ${err}`)}) }); }); } lib/server/app.js #!/usr/bin/env node const debug = require('debug')('freelancer:lib:server:app'); const express = require('express'); const logger = require('morgan'); const compression = require('compression'); const bodyParser = require('body-parser'); const helmet = require('helmet'); const vhost = require('vhost'); const responseTime = require('response-time'); const serveStatic = require('serve-static'); const path = require('path'); const middleware = require('./middleware'); const environment = require('./environment'); const data = require('./data'); const apps = require('../apps'); const app = express(); if (environment.logFormat) { app.use(logger(environment.logFormat)); } app.use('/healthcheck', function healthcheck(req, res) { return res.status(200).json({ status: 'success', data: { message: 'Healthcheck Ok' } }); }); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.set('env', environment.env); app.set('host', environment.host || 'localhost'); app.set('port', environment.port || 3000); if (environment.env === 'production') { app.set('trust proxy', true); } app.use(helmet()); app.use(middleware.addEnvironment); app.use(middleware.addUtils); app.use(middleware.logRequest); app.use(responseTime()); app.use(compression()); app.use(serveStatic(path.join(process.cwd(), 'public/common'))); app.use(bodyParser.json({ limit: '50mb' })); app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); app.use(middleware.setGoogleTmId); Object.keys(data.domains).forEach(function(appName) { const domain = data.domains[appName]; debug(`Adding vhost: ${domain} --> ${appName}`); app.use(vhost(domain, apps[appName])); }); app.use('/errors', express.static('./node_modules/server-error-pages/_site')); // catch 404 and forward to error handler app.use(function(req, res, next) { /*jshint unused: consts*/ const err = new Error('Not Found'); err.code = 404; return next(err); }); app.use(middleware.errorHandler); module.exports = app; const df = require("durable-functions"); module.exports = df.orchestrator(function* (context) { const work = []; const numActivities = context.df.getInput(); for(var i = 0; i < numActivities; i++){ work.push(context.df.callActivity("Hello", i.toString())); } yield context.df.Task.all(work) return "Done!"; });const router = require("express").Router(); const bcrypt = require("bcrypt"); const { Player } = require("../../models"); const withAuth = require("../../scripts/withAuth"); const withPlayerAuth = require("../../scripts/withPlayerAuth"); // Fetches players by either username, first name, and or last name router.get("/:str", async (req, res) => { try { const str = req.params.str; if(str.toLowerCase() === "admin" || str.toLowerCase() === "administrator") throw Error; let players = await Player.find( { first_name: { $regex: str, $options: "i" } }, "-password -isAdmin -phone -email" ).exec(); if (players.length === 0) { players = await Player.find( { last_name: { $regex: str, $options: "i" } }, "-password -isAdmin -phone -email" ).exec(); } if (players.length === 0) { players = await Player.find( { username: { $regex: str, $options: "i" } }, "-password -isAdmin -phone -email" ).exec(); } res.status(200).json(players); } catch (err) { console.error(err); res.status(400).json({ message: "ERROR when searching for player" }); } }); // Fetches single player data router.get("/id/:id", async (req, res) => { try { const dbPlayer = await Player.findById( { _id: req.params.id }, "-password -isAdmin -phone -email" ); res.status(200).json(dbPlayer); } catch (err) { console.error(err); res.status(500).json({ message: "ERROR when searching for player by id" }); } }); // Fetches all players from team router.get("/byteam/:teamid", async (req, res) => { try { const players = await Player.find( { team_key: Number.parseInt(req.params.teamid) }, "-password -isAdmin -phone -email" ); if (!players) res.status(404).json({ message: "No players on such team" }); res.status(200).json(players); } catch (err) { console.error(err); res .status(400) .json({ message: "ERROR when searching for players by team key" }); } }); // User Profile page api route MUST BE LOGGED IN TO USE // Fetches single player data router.get( "/user/profile/:id", /*withPlayerAuth*/ async (req, res) => { try { const dbPlayer = await Player.findById( { _id: req.params.id }, "-isAdmin" ); res.status(200).json(dbPlayer); } catch (err) { console.error(err); res .status(500) .json({ message: "ERROR when searching for player by id" }); } } ); // Update User Profile page route MUST BE LOGGED IN // Updates single user router.put( "/user/profile/update/:id", /*withPlayerAuth*/ async (req, res) => { try { const { params: { id }, body, } = req; console.log(body); const playerData = await Player.findOneAndUpdate({ _id: id }, body, { new: true, }); res.status(200).json(playerData); } catch (err) { console.error(err); res .status(400) .json({ message: "There was an ERROR when updating the player" }); } } ); //Updates password for player router.put( "/user/profile/change/password/:id", /*withPlayerAuth*/ async (req, res) => { try { // console.log(req.body); const { params: { id }, body, } = req; const hashedPassword = await bcrypt.hash(body.password, 10); const playerData = await Player.findOneAndUpdate( { _id: id }, { password: }, { new: true } ); res.status(200).json(playerData); } catch (err) { console.error(err); res .status(400) .json({ message: "There was an ERROR when updating the player" }); } } ); // Updates image for player router.put( "/user/profile/change/image/:id", withPlayerAuth, async (req, res) => { try { const { params: { id }, body, } = req; const playerData = await Player.findOneAndUpdate( { _id: id }, { image: body.imageURL }, { new: true } ); res.status(200).json(playerData); } catch (err) { console.error(err); res.status(400).json({ message: "ERROR when updating user image" }); } } ); // Admin access only // Can change all of the properties of any player router.put("/update/:id", withAuth, async (req, res) => { try { const { params: { id }, body, } = req; const playerData = await Player.findOneAndReplace( { _id: id }, { first_name: body.first_name, last_name: body.last_name, username: body.username, email: body.email, password: , date_of_birth: body.date_of_birth, phone: body.phone, image: body.image, position: body.position, jersey: body.jersey, team_key: body.team_key, stats: body.stats, isAdmin: body.isAdmin, }, { new: true } ); res.status(200).json(playerData); } catch (err) { console.error(err); res .status(400) .json({ message: "There was an ERROR when updating the player" }); } }); // Adds player to a team : ADMIN ONLY router.put("/update/player/team/:id", withAuth, async (req, res) => { try { const { params: { id }, body, } = req; const playerData = await Player.findOneAndUpdate( { _id: id }, { team_key: body.team_key }, { new: true } ); res.status(200).json(playerData); } catch (err) { console.error(err); res.status(400).json({ message: "ERROR when updating the players team" }); } }); // Update Players stats : ADMIN ONLY router.put("/update/player/stats/:id", withAuth, async (req, res) => { try { const { params: { id }, body, } = req; const playerData = await Player.findOneAndUpdate( { _id: id }, { stats: body.stats }, { new: true } ); res.status(200).json(playerData); } catch (err) { console.error(err); res.status(400).json({ message: "ERROR when updating the players stats" }); } }); module.exports = router; //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Show different HTML contents at the same time on each divided pane. //>>label: Split view //>>group: Tizen:Widgets define( [ 'jquery', '../jquery.mobile.tizen.scrollview' ], function ( ) { //>>excludeEnd("jqmBuildExclude"); /* *************************************************************************** * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *************************************************************************** * * Author: <> */ /** * Splitview is a widget which can show different HTML contents at the same time on each divided pane. * A user can place Splitview controls on JQuery Mobile's Content area and arrange two panes on the widget. * And HTML fragments or another Splitview also can be placed on the pane. * The number of panes inside of Splitview is restricted as two. * If a user define only one pane in Splitview, a empty pane will be added automatically, * on the other hand, if 3 or more panes are defined in Splitview, the panes after two will be ignored and removed from the DOM tree. * The HTML fragments of a pane should be composed of elements describing a part of Web page (e.g.
...
). * Also widgets can be included in the HTML fragments. * * HTML Attributes: * * data-fixed : The resizing mode of panes - fixed and flexible mode. * If the value is true, the panes' sizes will be fixed, or if not, it will be flexible. (Default : false) * data-divider-vertical : The direction of dividers. * If the value is true, the panes will be placed in horizontal direction, * or if not, it will be placed in vertical direction. (Default : "true") * data-ratio : The ratio of two panes' widths or heights. (Default : [ 1/2, 1/2 ] * * APIs: * * pane ( id [ , element ] ) * : This method replaces child contents of a pane indicated by id attribute with contents of inputted element. * If second argument is not specified, it will act as a getter method. * The string of id has to be started with "#" which means "id" of CSS selectors. * maximize ( id ) * : This method maximizes a pane's size indicated by id. * The string of id has to be started with "#" which means "id" of CSS selectors. * restore () * : This method restores all panes' sizes to the ratio prior to maximization. * * Examples: * *
*
pane0
*
pane1
*
* */ /** @class Splitview Splitview widget enables a user to place and arrange several panes. Each divided pane can show repective HTML contents. To add a Splitview widget to the application, use the following code:
pane0
pane1
*/ /** @property {Boolean} data-fixed The resizing mode of panes - fixed and flexible mode. */ /** @property {Boolean} data-divider-vertical The direction of dividers - horizontal or vertical. */ /** @property {Array} data-ratio The ratio of two panes' widths or heights. */ /** @method pane This method replaces child contents of a pane indicated by id attribute with contents of inputted element. If second argument is not specified, it will act as a getter method.
pane0
pane1
$(".selector").splitview("pane", id, element); */ /** @method maximize This method maximizes a pane's size indicated by id.
pane0
pane1
$(".selector").splitview("maximize", id); */ /** @method restore This method restores all panes' sizes to the ratio prior to maximization.
pane0
pane1
$(".selector").splitview("restore"); */ ( function ( $, window, document, undefined ) { $.widget( "tizen.splitview", $.mobile.widget, { options : { fixed : false, dividerVertical : true, ratio : [], initSelector : ":jqmData(role='splitview')" }, _create : function () { var self = this, $el = self.element, opt = self.options, $panes = $el.children( ".ui-pane" ), panesLength = $panes.length, spliters = [], spliterBars = [], ratioAttr = this.element.attr( "data-ratio" ), containerSize = [ 0, 0 ], resizeTimer = null, i = 0; if ( panesLength !== 2 ) { if ( panesLength < 2 ) { for ( i = panesLength ; i < 2 ; ++i ) { self._addEmptyPanes(); } } else { $panes.slice( 2 ).remove(); } $panes = $el.children( ".ui-pane" ); panesLength = $panes.length; } spliters[ 0 ] = $( "" ).insertAfter( $panes[ 0 ] ); spliterBars[ 0 ] = $( "
" ).appendTo( spliters[ 0 ] ); $( "
" ).appendTo( spliterBars[ 0 ] ); $.extend( this, { moveTarget : null, moveData : {}, spliters : spliters, spliterBars : spliterBars, panes : $panes, containerSize : containerSize, touchStatus : false, minPaneWidth : 50, savedRatio : [] }); self._bindTouchEvents(); self._convertRatio( ratioAttr, $panes.length ); $el.addClass( "ui-splitview ui-direction-" + self._direction( opt.dividerVertical ) ); self._refresh(); $( window ).unbind( ".splitview" ) .bind( "pagechange.splitview resize.splitview", function ( event ) { $( ".ui-page-active .ui-splitview" ).each( function () { $( this ).data( "splitview" )._refresh(); }); }); }, _addEmptyPanes : function () { var self = this, $el = self.element, opt = self.options, $panes = $el.children( ".ui-pane" ), scrollAttribute = ( $.support.scrollview ) ? "data-scroll='y'" : "", pane = $( "
" ); if ( scrollAttribute.length ) { pane.scrollview( { direction: "y" } ); } if ( !$panes.length ) { $el.append( pane ); } else { $panes.last().after( pane ); } }, _direction : function ( isHorizontal ) { return isHorizontal ? "horizontal" : "vertical"; }, _isStyleSpecified : function ( cssString ) { return ( typeof cssString !== "undefined" && cssString.length ); }, _getContainerSize : function ( widthString, heightString ) { var self = this, $el = self.element, widthSpecified = self._isStyleSpecified( widthString ), heightSpecified = self._isStyleSpecified( heightString ); self.containerSize[ 0 ] = ( widthSpecified ) ? $el.outerWidth( true ) : self._parentWidth(); self.containerSize[ 1 ] = ( heightSpecified ) ? $el.outerHeight( true ) : self._parentHeight(); if ( !self.containerSize[ 0 ] || !self.containerSize[ 1 ] ) { return false; } return true; }, _parentWidth : function () { var $parent = this.element.parent(); if ( !$parent && typeof $parent === "undefined" && !$parent.length ) { return $( window ).width(); } return $parent.width(); }, _parentHeight : function () { var $parent = this.element.parent(), heightString = "", heightSpecified = false, parentHeight = 0; while ( $parent && typeof $parent !== "undefined" && $parent.length ) { if ( typeof $parent[ 0 ].style !== "undefined" ) { heightString = $parent[ 0 ].style.height; heightSpecified = ( typeof heightString !== "undefined" && heightString.length ); if ( heightSpecified ) { parentHeight = $parent.height(); break; } } $parent = $parent.parent(); } if ( !heightSpecified ) { parentHeight = $(window).height(); } return parentHeight; }, _convertRatio : function ( ratioParam, panesLength ) { var self = this, ratio = [], loop = 0, type = typeof ratioParam, ratioArray = null, i; for ( i = 0; i < panesLength; ++i ) { ratio.push( 0 ); } switch ( type ) { case "number": if ( panesLength ) { ratio[ 0 ] = ratioParam; } break; case "string": ratioArray = ratioParam.split( "," ); loop = Math.min( ratioArray.length, panesLength ); for ( i = 0; i < loop; ++i ) { ratio[ i ] = parseFloat( ratioArray[ i ] ); } break; case "object": if ( !$.isArray( ratioParam ) ) { break; } loop = Math.min( ratioParam.length, panesLength ); for ( i = 0; i < loop; ++i ) { type = typeof ratioParam[ i ]; ratio[ i ] = ( type === "string" ) ? parseFloat( ratioParam[ i ] ) : ( type === "number" ) ? ratioParam[ i ] : 0; } break; } self.options.ratio = ratio; self._adjustRatio( panesLength ); }, _adjustRatio : function ( panesLength ) { var self = this, ratio = self.options.ratio, sum = 0, remain = 0, value = 0, subValue = 0, subRemain = 0, i; if ( !panesLength ) { self.options.ratio = []; return; } for ( i in ratio ) { sum += ratio[ i ]; } if ( sum !== 1 ) { remain = 1 - sum; value = remain / panesLength; for ( i in ratio ) { if ( value >= 0 ) { ratio[ i ] += value; remain = Math.max( 0, remain - value ); } else { subRemain += value; subValue = Math.max( subRemain, ratio[ i ] * -1 ); ratio[ i ] = Math.max( 0, ratio[ i ] + subValue ); remain = Math.min( 0, remain - subValue ); subRemain -= subValue; } } if ( remain ) { if ( remain > 0 ) { ratio[ ratio.length - 1 ] += remain; } else { for ( i = ratio.length - 1; i >= 0; --i ) { subValue = Math.max( remain, ratio[ i ] * -1 ); ratio[ i ] = Math.max( 0, ratio[ i ] + subValue ); remain = Math.min( 0, remain - subValue ); if ( !remain ) { break; } } } } self.options.ratio = ratio; } }, _setOption : function ( key, value ) { var self = this, orgValue = self.options[ key ]; if ( orgValue === value ) { return; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "fixed": self._fixed( value ); break; case "dividerVertical": self._dividerVertical( value ); break; case "ratio": self._ratio( value ); break; } }, _subtractDiffWidth : function ( width, diff ) { var self = this; if ( width <= self.minPaneWidth ) { return { width: width, diff: diff }; } width += diff; if ( width >= self.minPaneWidth ) { return { width: width, diff: 0 }; } return { width: self.minPaneWidth, diff: width - self.minPaneWidth }; }, _initRatio : function ( fromFirstPane, panes, isHorizontal, availableWidth ) { var self = this, sum = 0, widths = [], diff = 0, panesLength = panes.length, ret, i; panes.each( function ( i ) { var pane = $( this ); widths.push( isHorizontal ? pane.width() : pane.height() ); sum += widths[ i ]; }); diff = availableWidth - sum; if ( !diff ) { return widths; } if ( diff > 0 ) { widths[ fromFirstPane ? 0 : panesLength - 1 ] += diff; } else { if ( fromFirstPane ) { for ( i = 0; i < panesLength; ++i ) { ret = self._subtractDiffWidth( widths[ i ], diff ); widths[ i ] = ret.width; diff = ret.diff; if ( !diff ) { break; } } } else { for ( i = panesLength - 1; i >= 0; --i ) { diff = self._subtractDiffWidth( widths[ i ], diff ); widths[ i ] = ret.width; diff = ret.diff; if ( !diff ) { break; } } } } sum = 0; for ( i in widths ) { sum += widths[ i ]; } for ( i in self.options.ratio ) { self.options.ratio[ i ] = widths[ i ] / sum; } return widths; }, _horizontalBoundary : function () { var self = this, $el = self.element; return $el.outerWidth( true ) - $el.width(); }, _verticalBoundary : function () { var self = this, $el = self.element; return $el.outerHeight( true ) - $el.height(); }, _boundary : function ( type ) { var self = this, $el = self.element, computedStyle = window.getComputedStyle( $el[ 0 ], null ), margin = parseFloat( computedStyle[ "margin" + type ] ), border = parseFloat( computedStyle[ "border" + type + "Width" ] ), padding = parseFloat( computedStyle[ "padding" + type ] ); return { margin: margin, border: border, padding: padding }; }, _layout : function ( initRatio, fromFirstPane ) { var self = this, $el = self.element, opt = self.options, isHorizontal = opt.dividerVertical, $panes = self.panes, spliters = self.spliters, spliterBars = self.spliterBars, spliterBar = self.spliterBars.length ? $( spliterBars[ 0 ] ) : null, spliterWidth = !spliterBar ? 0 : isHorizontal ? spliterBar.outerWidth() : spliterBar.outerHeight(), spliterBarMargin = !spliterBar ? 0 : isHorizontal ? spliterBar.outerWidth( true ) - spliterBar.outerWidth() : spliterBar.outerHeight( true ) - spliterBar.outerHeight(), panesLength = $panes.length, currentAvailable = 0, spliterSize = spliterWidth * ( panesLength - 1 ), parentWidth = self.containerSize[ 0 ], parentHeight = self.containerSize[ 1 ], width = parentWidth - self._horizontalBoundary(), height = parentHeight - self._verticalBoundary(), innerSize = isHorizontal ? height : width, availableWidth = isHorizontal ? width - spliterSize : height - spliterSize, initializedWidth = [], widthSum = 0, childSplitview = null; initRatio = !!initRatio; fromFirstPane = !!fromFirstPane; $el.css( { "min-width" : width, "min-height" : height }); if ( initRatio ) { initializedWidth = self._initRatio( fromFirstPane, $panes, isHorizontal, availableWidth ); } currentAvailable = availableWidth; $panes.each( function ( i ) { var $pane = $( this ), paneWidth = initRatio ? initializedWidth[ i ] : Math.floor( availableWidth * self.options.ratio[i] ), prevPane = ( ( i ) ? $panes.eq( i - 1 ) : null ), posValue = 0, widthValue = 0, heightValue = 0, boundary = 0; currentAvailable -= paneWidth; if ( i === ( panesLength - 1 ) ) { if ( self.touchStatus ) { paneWidth = self.moveData.nextPaneWidth = availableWidth - ( self.moveData.targetPos + spliterWidth ); } else { paneWidth = Math.max( Math.min( paneWidth, self.minPaneWidth ), paneWidth + currentAvailable ); } } widthSum += paneWidth; if ( !prevPane ) { boundary = self._boundary( isHorizontal ? "Left" : "Top" ); posValue = boundary.padding; } else { posValue = parseInt( prevPane.css( isHorizontal ? "left" : "top" ), 10 ); posValue += isHorizontal ? prevPane.width() : prevPane.height(); posValue += spliterWidth; } widthValue = isHorizontal ? paneWidth : innerSize; heightValue = isHorizontal ? innerSize : paneWidth; $pane.css( { "width" : widthValue , "height" : heightValue } ); $pane.css( ( isHorizontal ? "left" : "top" ), posValue ); }); $panes.each( function ( i ) { var $pane = $( this ), paneWidth = isHorizontal ? $pane.width() : $pane.height(); self.options.ratio[ i ] = paneWidth / widthSum; }); $.each( spliters, function ( i ) { var spliter = $( this ), prevPane = $panes.eq( i ), bar = spliter.children( ".ui-spliter-bar" ), handle = bar.children( ".ui-spliter-handle" ), posValue = 0; if ( isHorizontal ) { posValue = parseInt( prevPane.css( "left" ), 10 ) + prevPane.width() - spliterBarMargin; spliter.outerHeight( innerSize ).css( "left", posValue ); } else { posValue = parseInt( prevPane.css( "top" ), 10 ) + prevPane.height() - spliterBarMargin; spliter.outerWidth( innerSize ).css( "top", posValue ); } if ( bar.length ) { bar[ isHorizontal ? "outerHeight" : "outerWidth" ]( innerSize ); } if ( handle.length ) { handle.css( isHorizontal ? "top" : "left", ( innerSize - spliterWidth ) / 2 ); } }); childSplitview = $el.find( ".ui-splitview:first" ); if ( !childSplitview.length ) { return; } childSplitview = childSplitview.data( "splitview" ); if ( childSplitview ) { childSplitview._refresh(); } }, _bindTouchEvents : function () { var self = this, $el = self.element, $panes = self.panes, spliters = self.spliters; $.each( spliters, function ( i ) { var spliter = $( this ); self._bindSpliterTouchEvents.call( self, spliter ); }); }, _bindSpliterTouchEvents : function ( spliter ) { var self = this, $el = self.element, opt = self.options, touchStartEvt = ( $.support.touch ? "touchstart" : "mousedown" ), touchMoveEvt = ( $.support.touch ? "touchmove" : "mousemove" ) + ".splitview", touchEndEvt = ( $.support.touch ? "touchend" : "mouseup" ) + ".splitview"; spliter.bind( touchStartEvt, { e : spliter }, function ( event ) { if ( self.options.fixed ) { return; } var realEvent = $.support.touch ? event.originalEvent.changedTouches[0] : event, targetSpliter = event.data.e, prevPane = targetSpliter.prev(), nextPane = targetSpliter.next(), splitviewInPrev = prevPane.find( ".ui-splitview:first" ), splitviewInNext = nextPane.find( ".ui-splitview:first" ), isHorizontal = opt.dividerVertical, spliterWidth = isHorizontal ? $( self.spliterBars[0] ).outerWidth() : $( self.spliterBars[0] ).outerHeight(); self.moveTarget = targetSpliter; self.moveData = { spliterWidth : spliterWidth || 0, prevPane : prevPane, nextPane : nextPane, splitviewInPrev : splitviewInPrev, splitviewInNext : splitviewInNext, prevPanePos : parseInt( prevPane.css( isHorizontal ? "left" : "top" ), 10 ) || 0, prevPaneWidth : parseInt( prevPane.css( isHorizontal ? "width" : "height" ), 10 ) || 0, nextPanePos : parseInt( nextPane.css( isHorizontal ? "left" : "top" ), 10 ) || 0, nextPaneWidth : parseInt( nextPane.css( isHorizontal ? "width" : "height" ), 10 ) || 0, targetPos : parseInt( targetSpliter.css( isHorizontal ? "left" : "top" ), 10 ) || 0, pagePos : isHorizontal ? realEvent.pageX : realEvent.pageY }; targetSpliter.addClass( "ui-spliter-active" ); $el.bind( touchMoveEvt, function ( event ) { if ( !self.touchStatus ) { return; } event.stopPropagation(); self._drag( $.support.touch ? event.originalEvent.changedTouches[0] : event ); }).bind( touchEndEvt, function ( event ) { event.stopPropagation(); self._stop( $.support.touch ? event.originalEvent.changedTouches[0] : event ); self.touchStatus = false; $el.unbind( ".splitview" ); $( document ).unbind( ".splitview" ); }); $( document ).bind( touchMoveEvt + " " + touchEndEvt, function () { $el.trigger( touchEndEvt ); }); event.preventDefault(); self.touchStatus = true; }); }, _drag : function ( e ) { if ( !this.moveData || typeof this.moveData === "undefined" ) { return; } var self = this, $el = self.element, opt = self.options, isHorizontal = opt.dividerVertical, moveData = self.moveData, moveTarget = self.moveTarget, prevPane = moveData.prevPane, nextPane = moveData.nextPane, splitviewInPrev = moveData.splitviewInPrev, splitviewInNext = moveData.splitviewInNext, spliterWidth = moveData.spliterWidth, movement = null, targetPos = null, nextPanePos = null, prevPaneWidth = null, nextPaneWidth = null, pagePos = isHorizontal ? e.pageX : e.pageY, splitview = null; movement = pagePos - moveData.pagePos; if ( movement > 0 ) { movement = Math.min( Math.max( moveData.nextPaneWidth - self.minPaneWidth, 0 ), movement ); } else { movement = Math.max( Math.max( moveData.prevPaneWidth - self.minPaneWidth, 0 ) * -1, movement ); } nextPanePos = moveData.nextPanePos + movement; prevPaneWidth = Math.max( moveData.prevPaneWidth + movement, 0 ); nextPaneWidth = Math.max( moveData.nextPaneWidth - movement, 0 ); targetPos = moveData.targetPos + movement; moveTarget.css( isHorizontal ? { left : targetPos } : { top : targetPos } ); prevPane.css( isHorizontal ? { width : prevPaneWidth } : { height : prevPaneWidth } ); nextPane.css( isHorizontal ? { width : nextPaneWidth, left : nextPanePos } : { height : nextPaneWidth, top : nextPanePos } ); if ( splitviewInPrev.length ) { splitview = splitviewInPrev.data( "splitview" ); splitview._refresh( true, false ); } if ( splitviewInNext.length ) { splitview = splitviewInNext.data( "splitview" ); splitview._refresh( true, true ); } }, _stop : function ( e ) { if ( !this.moveData || !this.moveTarget ) { return; } var self = this, $el = self.element, opt = self.options, $panes = self.panes, panesLength = $panes.length, isHorizontal = opt.dividerVertical, moveData = self.moveData, moveTarget = self.moveTarget, prevPane = moveData.prevPane, nextPane = moveData.nextPane, splitviewInPrev = moveData.splitviewInPrev, splitviewInNext = moveData.splitviewInNext, spliterWidth = moveData.spliterWidth, spliterSize = spliterWidth * ( panesLength - 1 ), movement = null, targetPos = null, nextPanePos = null, prevPaneWidth = null, nextPaneWidth = null, displayStyle = $el.css( "display" ), parentWidth = self.containerSize[ 0 ], parentHeight = self.containerSize[ 1 ], width = parentWidth - self._horizontalBoundary(), height = parentHeight - self._verticalBoundary(), availableWidth = isHorizontal ? ( width - spliterSize ) : ( height - spliterSize ), sum = 0; moveTarget.removeClass( "ui-spliter-active" ); // ratio calculation $panes.each( function ( i ) { var $pane = $( this ), paneWidth = isHorizontal ? $pane.width() : $pane.height(); sum += paneWidth; }); $panes.each( function ( i ) { var $pane = $( this ), paneWidth = isHorizontal ? $pane.width() : $pane.height(); self.options.ratio[ i ] = paneWidth / sum; }); self.moveData = null; }, _fixed : function ( isFix ) { var self = this, spliters = self.spliters; $.each( spliters, function ( i ) { var $spliter = $( this ); if ( isFix ) { $spliter.addClass( "ui-fixed" ); } else { $spliter.removeClass( "ui-fixed" ); } }); self._layout(); }, _dividerVertical : function ( isDividerVertical ) { var self = this, $el = self.element, isHorizontal = isDividerVertical, $panes = null, $spliters = null, $bar = null, $handle = null; $panes = $el.children( ".ui-pane" ); $spliters = $el.children( ".ui-spliter" ); $bar = $spliters.children( ".ui-spliter-bar" ); $handle = $bar.children( ".ui-spliter-handle" ); $el.removeClass( "ui-direction-vertical" ); $el.removeClass( "ui-direction-horizontal" ); $el.addClass( "ui-splitview ui-direction-" + self._direction( isHorizontal ) ); $panes.css( { "left" : "", "top" : "", "width" : "", "height" : "" }); $spliters.css( { "left" : "", "top" : "", "width" : "", "height" : "" }); $bar.css( { "width" : "", "height" : "" }); $handle.css( { "left" : "", "top" : "" }); if ( self._getContainerSize( $el[ 0 ].style.width, $el[ 0 ].style.height ) ) { self._layout(); } }, _ratio : function ( ratioParam ) { var self = this, $el = self.element, $panes = $el.children( ".ui-pane" ), panesLength = $panes.length; self._convertRatio( ratioParam, panesLength ); self._layout(); }, _refresh : function ( initRatio, fromFirstPane ) { var self = this, $el = self.element; initRatio = !!initRatio; fromFirstPane = !!fromFirstPane; if ( self._getContainerSize( $el[ 0 ].style.width, $el[ 0 ].style.height ) ) { self._layout( initRatio, fromFirstPane ); } }, pane : function ( id, element ) { if ( typeof id !== "string" ) { return null; } var self = this, $el = self.element, $targetPane = $el.children( id ), $targetView = null, elementParent = null; if ( !$targetPane.hasClass( "ui-pane" ) ) { return null; } // getter if ( !element ) { return $targetPane.contents(); } // setter if ( $targetPane.hasClass( "ui-scrollview-clip" ) ) { $targetPane.scrollview( "scrollTo", 0, 0, 0 ); $targetView = $targetPane.children( ".ui-scrollview-view" ); if ( !$targetView.length ) { return null; } } else { $targetView = $targetPane; } elementParent = element.parent(); if ( elementParent.length && elementParent[ 0 ] === $targetView[ 0 ] ) { return; } $targetView.empty().append( element ).trigger( "create" ); $targetView.fadeIn( 'fast' ); }, maximize : function ( id ) { if ( typeof id !== "string" ) { return; } var self = this, $el = self.element, $panes = self.panes, $targetPane = $el.children( id ); if ( !$targetPane.hasClass( "ui-pane" ) ) { return; } self.savedRatio = self.options.ratio.slice(); self.options.ratio = []; $panes.each( function ( i ) { self.options.ratio.push( ( this === $targetPane[ 0 ] ) ? 1 : 0 ); }); self._layout(); }, restore : function () { var self = this; if ( !self.savedRatio.length ) { return; } self.options.ratio = self.savedRatio.slice(); self._adjustRatio( self.panes.length ); self._layout(); } }); $( document ).bind( "pagecreate create", function ( e ) { $.tizen.splitview.prototype.enhanceWithin( e.target ); }); } ( jQuery, window, document ) ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); } ); //>>excludeEnd("jqmBuildExclude"); test/models/city/CityTest.js import City from '../../../src/models/city/City' const assert = require('assert') const sinon = require('sinon') describe('City tests', () => { var city beforeEach(() => { city = new City({ name: 'test', startPopulation: 100, startPrice: 10, popularityPct: 11, increaseAtOne: 1.25, increaseAtTwo: 2.25 }) }) it('Constructor works', () => { assert.equal(city.name, 'test') assert.equal(city.population, 100) assert.equal(city.turnipDemand.city, city) assert.equal(city.turnipDemand.popularityPct, 11) assert.equal(city.turnipDemand.constantPrice, 10) }) it('buyTurnips gives correct amount of cash', ()=>{ city.turnipDemand = {weekly: () => 5 } city.endOfTheYear = sinon.spy() assert.equal(5, city.buyTurnips(1, false)) assert.equal(0, city.endOfTheYear.callCount) }) it('Endoftheyear is called at the end of the year', ()=>{ city.turnipDemand = {weekly: () => 5 } city.endOfTheYear = sinon.spy() city.buyTurnips(1, true) assert.equal(1, city.endOfTheYear.callCount) }) it('Endoftheyear works', ()=>{ city.turnipDemand = {calculateYearlyDemand: sinon.spy(), percentageSupplied: () => 1} city.increasePopulation = sinon.spy() city.endOfTheYear() assert.equal(1, city.turnipDemand.calculateYearlyDemand.callCount) assert.equal(1, city.increasePopulation.callCount) assert(city.increasePopulation.calledWith(1)) }) describe('Population growth', ()=>{ it('50% supply does nothing', ()=>{ city.increasePopulation(0.5) assert.equal(100, city.population) }) it('Under 50% decreases correctly', ()=>{ city.increasePopulation(0) assert.equal(75, city.population) city.population = 100 city.increasePopulation(0.3) assert.equal(90, city.population) city.population = 100 city.increasePopulation(0.1) assert.equal(80, city.population) }) it('Between 50 and 100% increaes correctly', ()=>{ city.increasePopulation(1) assert.equal(125, city.population) city.population = 100 city.increasePopulation(0.8) assert.equal(115, city.population) city.population = 100 city.increasePopulation(0.6) assert.equal(105, city.population) }) it('Over 100% increases correctly', ()=>{ city.increasePopulation(2) assert.equal(225, city.population) city.population = 100 city.increasePopulation(1.5) assert.equal(175, city.population) city.population = 100 city.increasePopulation(3) assert.equal(325, city.population) }) it('Changing increaseAtWorks', ()=>{ city = new City({ name: 'test', startPopulation: 100, startPrice: 10, popularityPct: 11, increaseAtOne: 10, increaseAtTwo: 20 }) city.increasePopulation(1) assert.equal(1000, city.population) city.population = 100 city.increasePopulation(2) assert.equal(2000, city.population) city.population = 100 city.increasePopulation(0.5) assert.equal(100, city.population) city.population = 100 city.increasePopulation(0) assert.equal(-800, city.population) }) }) }) var express=require('express'); var webpush=require('web-push'); var path=require('path'); var app=express(); app.use(express.static(path.join(__dirname,'node-push-notifications-client'))); var bodyParser=require('body-parser'); //var urlencodedParser=bodyParser.urlencoded({extended: true}); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); const publicKey=''; const privateKey=''; webpush.setVapidDetails('mailto:',publicKey,privateKey); app.post('/subscribe',function(req,res){ console.log('came here'); console.log(req.body) const subscription=req.body; res.status(201).json({}); const payload=JSON.stringify({title:'Push Test'}); webpush.sendNotification(subscription,payload).catch(function(err){ console.log('yh h kya error'); }); }); app.listen('8080');// ssng.js for SSNG(client side) // 2019.04.11 const serverURL = "/ssng/"; let tid = 0; let packetId = 0; let active_packet_id = ''; let dataLogArray = []; let analyzedData = ""; var vm = new Vue({ el: '#app', data: { ipServer: "", ipData: "172.16.58.3", el: { deojData: "0x013001", esvData: "0x62", epcData: "0x80", edtData: "0x30" }, freeData: "10,81,00,0A,05,FF,01,01,30,01,62,01,80,00", ipDataStyle: {color: 'black'}, deojDataStyle: {color: 'black'}, esvDataStyle: {color: 'black'}, epcDataStyle: {color: 'black'}, edtDataStyle: {color: 'black'}, freeDataStyle: {color: 'black'}, rbInputData: "el", rbOrder: "normalOrder", filters: ["showGet", "showInf", "showGetres", "showSNA"], packet_list: [], packetDetail: "" }, methods: { buttonClickSearch: function () { buttonClickSearch(); }, buttonClickSend: function () { buttonClickSend(this.ipData, this.el, this.freeData); }, updateRbOrder: function () { displayLog(); }, updateFilters: function () { displayLog(); }, clearLog: function () { clearLog(); }, saveLog: function () { saveLog(); }, // パケット一覧からパケット行がクリックされたときの処理 (パケット詳細を表示) showPacketDetail: this.packetMonitorShowPacketDetail.bind(this), // パケット一覧で矢印キーが押されたときの処理 upDownList: this.packetMonitorUpDownList.bind(this) } }); // Show server IP address let request = new XMLHttpRequest(); request.addEventListener("load", reqListener); request.open('GET', 'ssng/ipv4'); request.send(); function reqListener () { vm.ipServer = this.responseText; } // connect websocket console.log('ws://' + document.location.host); let ws = new WebSocket('ws://' + document.location.host); ws.onopen = function(event){ console.log("connected"); }; ws.onmessage = function(event){ console.log("server_to_client", event.data); const obj = JSON.parse(event.data); if (obj.ip != vm.ipServer ) { const packet_id = 'packet-' + packetId++; const pkt = { id:packet_id, timeStamp:timeStamp(), direction:"R", ip:obj.ip, data:obj.uint8Array } dataLogArray.push(pkt); displayLog(); } }; function displayLog() { let log = []; for (let dataLog of dataLogArray) { const esv = dataLog.data[10]; const pkt = { id: dataLog.id, timeStamp: dataLog.timeStamp, direction: dataLog.direction, address: dataLog.ip, hex: elFormat(dataLog.data) } if ((dataLog.direction == "T") || filterEsv(esv)) { log.push(pkt); } } if (vm.rbOrder == "reverseOrder") { log.reverse(); } vm.packet_list = log; // clear packet selection if (this.active_packet_id) { $('#' + this.active_packet_id).removeClass('active'); this.active_packet_id = ''; } vm.packetDetail = ""; return; function filterEsv(esv) { if (!vm.filters.includes("showGet") && (esv == 0x62)) { return false; } if (!vm.filters.includes("showInf") && (esv == 0x73)) { return false; } if (!vm.filters.includes("showGetres") && (esv == 0x72)) { return false; } if (!vm.filters.includes("showSNA") && ((esv == 0x50) || (esv == 0x51) || (esv == 0x52) || (esv == 0x53) || (esv == 0x5E))) { return false; } return true; } } function timeStamp() { const date = new Date(); let hour = date.getHours().toString(); let minute = date.getMinutes().toString(); let second = date.getSeconds().toString(); hour = (hour.length == 1) ? ("0" + hour) : hour; minute = (minute.length == 1) ? ("0" + minute) : minute; second = (second.length == 1) ? ("0" + second) : second; return hour + ":" + minute + ":" + second; } function analyzeData(uint8Array) { // uint8Array: [UInt8] let analyzedData = ""; let epcArray = []; const esv = uint8Array[10]; const epc = uint8Array[12]; const edt = uint8Array.slice(14); // Decode PropertyMap if (shouldDecodePropertyMap()) { if (edt.length < 17) { // PropertyMapがEPCの列挙の場合 for (let i=1; i "0A" // example: toStringHex(10, 2) => "000A" function toStringHex(number, bytes) { let str = number.toString(16).toUpperCase(); while (str.length < 2*bytes) { str = "0" + str; } return str; } // stringに文字列を挿入 function strIns(str, idx, val){ // str:string(元の文字列), idx:number(挿入する位置), val:string(挿入する文字列) var res = str.slice(0, idx) + val + str.slice(idx); return res; } // Check input value of text field // argument: inputType:string, enum("ip", "deoj", "esv", "epc", "edt", "free") // get text data from text input field of "inputType" // return value: boolean function checkInputValue(inputType, inputValue) { let regex; switch (inputType) { case "ip": regex = /^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/; break; case "deoj": regex = /^(0x)?(\d|[a-f]|[A-F]){6}$/; break; case "esv": case "epc": regex = /^(0x)?(\d|[a-f]|[A-F]){2}$/; break; case "edt": regex = /^((0x)?((\d|[a-f]|[A-F]){2}){1,})?$/; break; case "free": regex = /^((\d|[a-f]|[A-F]){2},\s*){1,}(\d|[a-f]|[A-F]){2}\s*$/; break; default: } if (regex.test(inputValue)) { return true; }else{ return false; } } function buttonClickSend(ipData, el, freeData) { if (!checkInputValue('ip', vm.ipData)) { vm.ipDataStyle.color = "red"; window.alert("Check IP address"); return false; } else { vm.ipDataStyle.color = "black"; } let uint8Array = []; let binaryString = ""; uint8Array = (vm.rbInputData == "el") ? createUint8ArrayFromElData(el) : createUint8ArrayFromFreeData(freeData); if (uint8Array !== false) { const message = {ip:ipData, uint8Array:uint8Array}; const request = new XMLHttpRequest(); request.open('PUT', serverURL + 'send'); request.setRequestHeader("Content-type", "application/json"); request.send(JSON.stringify(message)); // push "Sent Data" to LOG const packet_id = 'packet-' + packetId++; const pkt = { id:packet_id, timeStamp:timeStamp(), direction:"T", ip:ipData, data:uint8Array } dataLogArray.push(pkt); displayLog(); } } function createUint8ArrayFromElData(el) { if (!checkInputValue('deoj', vm.el.deojData)) { vm.deojDataStyle.color = "red"; window.alert("Check DEOJ"); return false; } else { vm.deojDataStyle.color = "black"; } if (!checkInputValue('esv', vm.el.esvData)) { vm.esvDataStyle.color = "red"; window.alert("Check ESV"); return false; } else { vm.esvDataStyle.color = "black"; } if (!checkInputValue('epc', vm.el.epcData)) { vm.epcDataStyle.color = "red"; window.alert("Check EPC"); return false; } else { vm.epcDataStyle.color = "black"; } if (!checkInputValue('edt', vm.el.edtData)) { vm.edtDataStyle.color = "red"; window.alert("Check EDT"); return false; } else { vm.edtDataStyle.color = "black"; } let uint8Array = [0x10, 0x81]; // EHD tid = (tid == 0xFFFF) ? 0 : (tid+1); uint8Array.push(Math.floor(tid/16), tid%16); // TID uint8Array.push(0x05, 0xFF, 0x01); // SEOJ for (let data of hex2Array(el.deojData)) { // DEOJ uint8Array.push(data); } uint8Array.push(parseInt(el.esvData, 16)); // ESV uint8Array.push(0x01); // OPC uint8Array.push(parseInt(el.epcData, 16)); // EPC const esv = parseInt(el.esvData, 16); if ((esv == 0x62) || (esv == 0x63) || (esv == 0x71) || (esv == 0x7A) || (esv == 0x7E) || (esv == 0x50) || (esv == 0x51) || (esv == 0x52) || (esv == 0x53) || (esv == 0x5E)) { uint8Array.push(0x00); // PDC } else { // EPC= 0x60:SetI, 0x61:SetC, 0x6E:SetGet, 0x72:Get_Res, 0x73:INF, 0x74:INFC, const edtArray = hex2Array(el.edtData) uint8Array.push(edtArray.length); // PDC for (let data of hex2Array(el.edtData)) { // EDT uint8Array.push(data); } } return uint8Array; } function hex2Array(hex) { // hex: string of this format 0xXXXX or XXXX if (hex.slice(0,2) != "0x") { hex = "0x" + hex; } let array =[]; const bytes = (hex.length - 2)/2; for (let i=0; i= dataLogArray.length ) {pno = dataLogArray.length -1} } } else if (c === 40 || k === 'ArrowDown') { // 下矢印キー if (vm.rbOrder == "normalOrder") { if (pno++ >= dataLogArray.length ) {pno = dataLogArray.length -1} } else { if (pno-- <0 ) {pno = 0} } } else { return; } // 遷移したパケット行にフォーカスする $('#packet-' + pno).focus(); }import PluginError from 'plugin-error'; import {Transform} from 'stream'; import {optimize} from 'svgo'; import {getSvgoConfig} from './get-svgo-config.js'; const PLUGIN_NAME = 'gulp-svgmin'; module.exports = function (options) { const optionsFunction = typeof options === 'function'; const stream = new Transform({objectMode: true}); stream._transform = function (file, encoding, cb) { if (file.isStream()) { return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported')); } if (file.isBuffer()) { getSvgoConfig( optionsFunction ? options(file) : options, optionsFunction ) .then((config) => { const result = optimize(String(file.contents), config); // Ignore svgo meta data and return the SVG string. if (typeof result.data === 'string') { file.contents = Buffer.from(result.data); return cb(null, file); } // Otherwise, throw an error, even if it is undefined. throw result.error; }) .catch((error) => cb(new PluginError(PLUGIN_NAME, error))); return; } // Handle all other cases, like file.isNull(), file.isDirectory(). return cb(null, file); }; return stream; }; var observableModule = require("tns-core-modules/data/observable"); function StatusViewModel() { var viewModel = observableModule.fromObject({ onButtonTap: function () { console.log("Button was pressed"); }, }); return viewModel; } module.exports = StatusViewModel; var module = angular.module('app', []); module.controller('constr', ['$scope', '$http', function ($scope, $http) { /* * Создать showMessage! * */ $scope.changelvl = -1; $scope.map = []; // $scope.player = new Player(110,110,110,110,10,"down"); $scope.player = []; $scope.go = false; $scope.showPoppup = false; $scope.newLvl = false; //poppup $scope.showEditLvl = false; //poppup $scope.showChangeMap = false; //poppup $scope.remakeLvl=""; $scope.editcollisionind = 0; $scope.editcollision; $scope.lvls_urls = []; $.when($.ajax({ url: "/public/store/xmls/lvl1.xml", type: "POST" }), $.ajax({ url: "/src/controller/getMapImgs.php", type: "POST", dataType: "json" })).done(function(a1, a2) { $scope.lvls = parseLvl(a1); $scope.changelvl = 0; var temp = a2[0]; temp.splice(0,1); temp.splice(0,1); $scope.lvls_urls = temp; console.log("this ---->>>>>",temp); updateScope(); }); $scope.createNewLvl = function () { var name = $("#projName").val(); var width = $("#projWidth").val(); var height = $("#projHeight").val(); var id = $scope.lvls.lvls.length; $scope.map = { "name": name, "collision":[], "height":height, "width":width, "id": id }; $scope.lvls.lvls.push($scope.map); $scope.changelvl = id; $scope.showPoppup = false; $scope.newLvl = false; // var text_xml = ""+name+""+width+""+height+""; // // $.ajax({ // url: "/src/controller/AjaxController.php", // type: "POST", // data: { // 'action': "createLvl", // 'data': text_xml // }, // success: function () { // console.log("save"); // } // }); }; $scope.saveAll = function () { var text_xml = ""; for(var lvl in $scope.lvls.lvls){ text_xml+= ""+$scope.lvls.lvls[lvl].name+"" + ""+$scope.lvls.lvls[lvl].map+"" + ""+$scope.lvls.lvls[lvl].width+"" + ""+$scope.lvls.lvls[lvl].height+""; for(var col in $scope.lvls.lvls[lvl].collision){ text_xml+= ""+$scope.lvls.lvls[lvl].collision[col].posX+"" + ""+$scope.lvls.lvls[lvl].collision[col].posY+"" + ""+$scope.lvls.lvls[lvl].collision[col].width+"" + ""+$scope.lvls.lvls[lvl].collision[col].height+"" } text_xml+=""; } text_xml+=""; $.ajax({ url: "/src/controller/AjaxController.php", type: "POST", data: { 'action': "saveLvls", 'data': text_xml }, success: function () { console.log("save"); } }); }; $scope.delLvl = function () { $scope.lvls.lvls.splice($scope.changelvl, 1); $scope.changelvl = 0; }; $scope.keyDown = function (event) { switch (event.which){ case 87: //W; $scope.goes("up"); break; case 83: //S $scope.goes("down"); break; case 65: //A $scope.goes("left"); break; case 68: //D $scope.goes("right"); break; } }; $scope.keyUp = function () { $scope.go = false; }; $scope.goes = function (vector) { $scope.go = true; switch (vector){ case "up": $scope.player.posY -= $scope.player.speed; if($scope.touchPlMp($scope.player)) $scope.player.posY += $scope.player.speed; $scope.player.rot = "up"; break; case "down": $scope.player.posY += $scope.player.speed; if($scope.touchPlMp($scope.player)) $scope.player.posY -= $scope.player.speed; $scope.player.rot = "down"; break; case "left": $scope.player.posX -= $scope.player.speed; if($scope.touchPlMp($scope.player)) $scope.player.posX += $scope.player.speed; $scope.player.rot = "left"; break; case "right": $scope.player.posX += $scope.player.speed; if($scope.touchPlMp($scope.player)) $scope.player.posX -= $scope.player.speed; $scope.player.rot = "right"; break; } }; $scope.touchObj = function (obj1, obj2) { var gap = 0; return !(Number(obj1.posY) + Number(obj1.height) < Number(obj2.posY)|| Number(obj1.posX) + Number(obj1.width) < Number(obj2.posX) || Number(obj1.posY) + gap > Number(obj2.posY) + Number(obj2.height)|| Number(obj1.posX) + gap > Number(obj2.posX) + Number(obj2.width)); }; $scope.touchPlMp = function (player) { for(var col in $scope.map.collision) if($scope.touchObj(player, $scope.map.collision[col])) return true; return false; }; $scope.getTouchPlMp = function (player) { for(var col in $scope.map.collision) if($scope.touchObj(player, $scope.map.collision[col])) return $scope.map.collision[col]; return false; }; $scope.$watch('player.posY', function () { var scrollTop = $scope.player.posY - $('#display').height()/2 + $scope.player.height; $('#display').animate({ scrollTop: scrollTop}, 0); }); $scope.$watch('player.posX', function () { var scrollLeft = $scope.player.posX - $('#display').width()/2 + $scope.player.width; $('#display').animate({ scrollLeft: scrollLeft }, 0); }); $scope.$watch('changelvl', function (newValue) { console.log(newValue); if($scope.lvls!=undefined) { $scope.map = $scope.lvls.lvls[newValue]; } }); $scope.showEditMenu = function (index) { $scope.editcollisionind = index; $scope.editcollision = $scope.map.collision[index]; $("#colision-table tbody tr").removeClass("cadetblue"); $("#colision-table tbody tr.col-"+index).addClass("cadetblue"); $(".in_lvl").removeClass("green"); $("#col-"+index).addClass("green"); }; $scope.delCol = function(index){ $scope.map.collision.splice(index, 1); }; $(document).ready(function (){ var mouseDown = false; var mouseUp = true; var elem_left = $("#game").offset().left; var elem_top = $("#game").offset().top; var scrollLeft = $('#display').scrollLeft(); var scrollTop = $('#display').scrollTop(); var posX; var posY; var res = null; // Для изменения размеров var resizeCan = false; var resizeSide = 0; var resizeObject = null; var resizePos = []; // ____ $("#game").on("mousedown", function (e) { if(mouseUp ) { mouseUp = false; mouseDown = true; if ($scope.remakeLvl=='addColl'){ scrollLeft = $('#display').scrollLeft(); scrollTop = $('#display').scrollTop(); posX = e.pageX - elem_left + scrollLeft; posY = e.pageY - elem_top + scrollTop; $(this).append("
"); res = $(".new_block"); $(res).css('top', posY); $(res).css('left', posX); } if ($scope.remakeLvl == 'moveCollUnclick'){ // posX = e.pageX - elem_left + scrollLeft; // posY = e.pageY - elem_top + scrollTop; // // var curr = new Player(posX,posY,1,1); // res = $scope.getTouchPlMp(curr); // console.log(res); $scope.remakeLvl = 'moveCollClick'; updateScope(); } if ($scope.remakeLvl == 'addPlayer'){ scrollLeft = $('#display').scrollLeft(); scrollTop = $('#display').scrollTop(); posX = e.pageX - elem_left + scrollLeft; posY = e.pageY - elem_top + scrollTop; $(this).append("
"); res = $(".new_block_backPl"); $(res).css('top', posY); $(res).css('left', posX); } } }); $("#game").on("mousemove", function (e2) { if(mouseDown) { scrollLeft = $('#display').scrollLeft(); scrollTop = $('#display').scrollTop(); if ($scope.remakeLvl=='addColl'){ var posX2 = e2.pageX - elem_left + scrollLeft; var posY2 = e2.pageY - elem_top + scrollTop; if (posX2 > posX && posY2 < posY) { $(".new_block").width(posX2 - posX); $(".new_block").css('top', posY2); $(".new_block").css('left', posX); $(".new_block").height(posY - posY2); } else if (posX2 < posX && posY2 < posY) { $(".new_block").css('top', posY2); $(".new_block").css('left', posX2); $(".new_block").width(posX - posX2); $(".new_block").height(posY - posY2); } else if (posX2 < posX && posY2 > posY) { $(".new_block").css('left', posX2); $(".new_block").css('top', posY); $(".new_block").width(posX - posX2); $(".new_block").height(posY2 - posY); } else if (posX2 > posX && posY2 > posY) { $(".new_block").width(posX2 - posX); $(".new_block").height(posY2 - posY); $(".new_block").css('left', posX); $(".new_block").css('top', posY); } else { $(".new_block").width(0); $(".new_block").height(0); } } if($scope.remakeLvl = "addPlayer") { var posX2 = e2.pageX - elem_left + scrollLeft; var posY2 = e2.pageY - elem_top + scrollTop; if (posX2 > posX && posY2 < posY) { $(".new_block_backPl").width(posX2 - posX); $(".new_block_backPl").css('top', posY2); $(".new_block_backPl").css('left', posX); $(".new_block_backPl").height(posY - posY2); } else if (posX2 < posX && posY2 < posY) { $(".new_block_backPl").css('top', posY2); $(".new_block_backPl").css('left', posX2); $(".new_block_backPl").width(posX - posX2); $(".new_block_backPl").height(posY - posY2); } else if (posX2 < posX && posY2 > posY) { $(".new_block_backPl").css('left', posX2); $(".new_block_backPl").css('top', posY); $(".new_block_backPl").width(posX - posX2); $(".new_block_backPl").height(posY2 - posY); } else if (posX2 > posX && posY2 > posY) { $(".new_block_backPl").width(posX2 - posX); $(".new_block_backPl").height(posY2 - posY); $(".new_block_backPl").css('left', posX); $(".new_block_backPl").css('top', posY); } else { $(".new_block_backPl").width(0); $(".new_block_backPl").height(0); } } if ($scope.remakeLvl == 'moveCollClick'){ var posX2 = e2.pageX - elem_left + scrollLeft; var posY2 = e2.pageY - elem_top + scrollTop; res.posX += posX2 - posX; res.posY += posY2 - posY; //res.width += posX2 - posX; //res.height += posY2 - posY; posX = posX2; posY = posY2; updateScope(); } } if (($scope.remakeLvl == 'moveColl' || $scope.remakeLvl == 'moveCollUnclick') && mouseUp){ posX = e2.pageX - elem_left + scrollLeft; posY = e2.pageY - elem_top + scrollTop; var curr = new Player(posX,posY,1,1); res = $scope.getTouchPlMp(curr); if(res){ $scope.remakeLvl = 'moveCollUnclick'; }else{ $scope.remakeLvl = 'moveColl'; } updateScope(); } else if ($scope.remakeLvl === 'resizeColl') { posX = e2.pageX - elem_left + scrollLeft; posY = e2.pageY - elem_top + scrollTop; var curr = new Player(posX,posY,1,1); res = $scope.getTouchPlMp(curr); if (mouseDown && resizeCan) { // Если объект для изменений новый => помещаем в перменные для нормального перемещения по карте. if (resizeObject === null) { resizeObject = res; resizePos = [resizeObject.posY, resizeObject.width, resizeObject.height, resizeObject.posX]; } if (resizeSide === 1) { // Вверх resizeObject.posY = posY; resizeObject.height = resizePos[0] + resizePos[2] - posY; } else if (resizeSide === 2) { // Вправо resizeObject.width = posX - resizeObject.posX; } else if (resizeSide === 3) { // Вниз resizeObject.height = posY - resizeObject.posY; } else if (resizeSide === 4) { // Влево resizeObject.posX = posX; resizeObject.width = resizePos[1] + resizePos[3] - posX; } // Избавляемся от отрицательных значений if (resizeObject.height < 1) resizeObject.height = 5; else if (resizeObject.width < 1) resizeObject.width = 5; updateScope(); } else { resizeCan = true; // Назначаем сторону для изменения размеров if (res.posY + 5 > posY) { $("body").css('cursor', 's-resize'); resizeSide = 1; } else if (posX + 5 > res.width + res.posX) { $("body").css('cursor', 'e-resize'); resizeSide = 2; } else if (posY + 5 > res.height + res.posY) { $("body").css('cursor', 's-resize'); resizeSide = 3; } else if (res.posX + 5 > posX) { $("body").css('cursor', 'e-resize'); resizeSide = 4; } else { $("body").css('cursor', 'context-menu'); resizeCan = false; } } } }); $("#game").on("mouseup", function () { if(mouseDown) { if ($scope.remakeLvl=='addColl'){ var posX = $(res).css('left'); var posY = $(res).css('top'); posX = posX.substr(0, posX.length - 2); posY = posY.substr(0, posY.length - 2); if($scope.map.collision != undefined) $scope.map.collision.push({ "posX": Number(posX), "posY": Number(posY), "width": $(res).width(), "height": $(res).height() }); else $scope.map.collision = [{ "posX": Number(posX), "posY": Number(posY), "width": $(res).width(), "height": $(res).height() }]; $(res).remove(); } if ($scope.remakeLvl=='addPlayer'){ var posX = $(res).css('left'); var posY = $(res).css('top'); // posX = posX.substr(0, posX.length - 2); // posY = posY.substr(0, posY.length - 2); // if($scope.map.collision != undefined) // $scope.map.collision.push({ // "posX": Number(posX), // "posY": Number(posY), // "width": $(res).width(), // "height": $(res).height() // }); // else // $scope.map.collision = [{ // "posX": Number(posX), // "posY": Number(posY), // "width": $(res).width(), // "height": $(res).height() // }]; // // $(res).remove(); } if ($scope.remakeLvl == 'moveCollClick'){ $scope.remakeLvl = 'moveColl'; } mouseUp = true; mouseDown = false; updateScope(); res = null; } // Удаляем данные, если перемещение объекта завершенно if ($scope.remakeLvl === 'resizeColl' && resizeObject !== null) { resizePos = []; resizeObject = null; } }); $("#exitConstructor").on("click", function () { //выйти из конструктора document.cookie = "constructor=; path=/;"; location.reload(); }); $(".dropzone").on("click",function () { $("#loadMap").click(); }); var files; $('#loadMap').on("change", function(){ files = this.files; $("#upload-image").submit(); }); $('#upload-image').on('submit',(function(e) { var data = new FormData(); $.each( files, function( key, value ){ data.append( key, value ); }); sendImage(data, e) })); $(".dropzone").on('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); $(".dropzone > div").text("Отпустите!"); }); $(".dropzone").on('dragover', function (e) { e.stopPropagation(); e.preventDefault(); $(".dropzone > div").text("Перетащите или кликните."); }); $(".dropzone").on('drop', function (e) { e.stopPropagation(); e.preventDefault(); console.log(e); if(!e.originalEvent.dataTransfer) return; var re = /(.jpg|.jpeg|.bmp|.gif|.png)$/i; if (!re.exec(e.originalEvent.dataTransfer.files[0].name)) { $(".dropzone > div").text("Недопустимый формат файла!"); }else { var fd = new FormData(); $.each(e.originalEvent.dataTransfer.files, function( key, value ){ fd.append( key, value ); }); sendImage(fd, e); } }); }); function sendImage(data, e) { e.preventDefault(); e.preventDefault(); $.ajax({ type:'POST', // Тип запроса url: '/src/controller/saveImg.php', // Скрипт обработчика data: data, // Данные которые мы передаем cache:false, // В запросах POST отключено по умолчанию, но перестрахуемся contentType: false, // Тип кодирования данных мы задали в форме, это отключим processData: false, // Отключаем, так как передаем файл dataType: 'json', success:function(data){ $(".dropzone > div").text("Файл успешно загружен!"); $scope.lvls_urls.push(data.files[0].split("lvl-maps\\")[1]); console.log("its - >", data.files[0].split("lvl-maps\\")[1], "and", $scope.lvls_urls); updateScope(); }, error:function(){ $(".dropzone > div").text("Произошла ошибка, повторите снова или перезагрузите страницу."); } }); } }]); function Player(posX, posY, width, height, speed, rot) { this.posX = posX; this.posY = posY; this.width = width; this.height = height; this.gap = 20; this.speed = speed; this.rot = rot; } function GoToOtherLvl(posX, posY, width, height) { this.posX = posX; this.posY = posY; this.width = width; this.height = height; this.gap = 20; } function parseLvl(xml) { var arr = {}; arr.lvls = []; $(xml).find("lvl").each(function (lvl_i, lvl){ arr.lvls[lvl_i] = {}; arr.lvls[lvl_i].collision = []; $(lvl).find("collision").each(function (idx, v) { arr.lvls[lvl_i].collision[idx] = {}; $(v).find("posX").each(function (i, vi) { arr.lvls[lvl_i].collision[idx].posX = Number($(vi).text()); }); $(v).find("posY").each(function (i, vi) { arr.lvls[lvl_i].collision[idx].posY = Number($(vi).text()); }); $(v).find("width").each(function (i, vi) { arr.lvls[lvl_i].collision[idx].width = Number($(vi).text()); }); $(v).find("height").each(function (i, vi) { arr.lvls[lvl_i].collision[idx].height = Number($(vi).text()); }); }); arr.lvls[lvl_i].width = $(lvl).find("lvl > width").text(); arr.lvls[lvl_i].height = $(lvl).find("lvl > height").text(); arr.lvls[lvl_i].name = $(lvl).find("lvl > name").text(); arr.lvls[lvl_i].map = $(lvl).find("lvl > map").text(); arr.lvls[lvl_i].id = lvl_i; }); return arr; } function updateScope() { $("#update").click(); } src/content.js const parsePrice = (price) => { return price.replace(/^\D+/g, ""); }; const computeFootprint = (price) => { const co2PerDollar = 122.8; return (price * co2PerDollar).toFixed(2); }; const getAmazonPrice = () => { var rawPrice = document.getElementById("priceblock_ourprice").innerHTML; var price = parsePrice(rawPrice); return price; }; const getEbayPrice = () => { // TODO: In the future, to compute the footprint for other popular e-commercesi var rawPrice = document.getElementById("mm-saleDscPrc").innerHTML; var price = parsePrice(rawPrice); return price; }; const injectAmazonFootprint = (footprint) => { const price = document.getElementById("priceblock_ourprice"); const title = `Estimated 👣 = ${footprint}g`; const titleBlock = document.createElement("span"); const icon = document.createElement("img"); icon.src = "https://i.ibb.co/LRNV941/40.png"; icon.setAttribute("style", "height: 30px"); titleBlock.textContent = title; titleBlock.setAttribute("style", "font-size: 14px; color: black"); price.appendChild(document.createElement("br")); price.appendChild(icon); price.appendChild(titleBlock); price.appendChild(document.createElement("br")); }; const fetchPriceFromVendor = () => { const amazonPrice = getAmazonPrice(); const result = computeFootprint(amazonPrice); injectAmazonFootprint(result); }; fetchPriceFromVendor(); 'use strict'; const fs = require('fs'); const express = require('express'); const fileUpload = require('express-fileupload'); const PORT = process.env.PORT || 3000; const app = express(); // default options app.use(fileUpload()); app.get('/', function (req, res) { res.sendFile(__dirname + '/public/index.html'); }); // creates upload directory if it does not exist. let dir = './uploads'; if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } // express-fileupload application. app.post('/upload', function (req, res) { if (!req.files) return res.status(400).send('No files were uploaded.'); // The name of the input field (i.e "sampleFile") is used to retrieve the uploaded file. let sampleFile = req.files.sampleFile; // use the mv() method to place the file somewhere on your server. sampleFile.mv(`./uploads/${sampleFile.name}`, function (err) { console.log(sampleFile); if (err) return res.status(500).send(err); // checks the file size let stats = fs.statSync(`./uploads/${sampleFile.name}`); let fileSizeInBytes = stats.size; // res.send(`${sampleFile.name} Uploaded! ${fileSizeInBytes} Bytes`); res.sendFile(__dirname + '/public/index.html'); // res.send(uploadComplete()); }); }); // Starts the server. app.listen(PORT, () => { console.log('Listening on port:', PORT, 'use CTRL+C to close.'); });var path = require('path'); var Queue = require('queue-cb'); var installNode = require('./installNode'); var installNPM = require('./installNPM'); var checkMissing = require('./checkMissing'); var ensureDestinationParent = require('./ensureDestinationParent'); module.exports = function install(version, dest, options, callback) { // use cwd if dest not provided if (!dest) dest = path.join(process.cwd(), version.version); checkMissing(dest, options, function (err, missing) { if (err || !missing.length) return callback(err, dest); var queue = new Queue(1); queue.defer(ensureDestinationParent.bind(null, dest)); !~missing.indexOf('node') || queue.defer(installNode.bind(null, version, dest, options)); !~missing.indexOf('npm') || queue.defer(installNPM.bind(null, version, dest, options)); queue.await(function (err) { err ? callback(err) : callback(null, dest); }); }); }; const Engine = require('../lib') const engine = new Engine({ root: `${__dirname}/fixtures/simple` }) const { test } = require('tap') test('no-data', assert => { assert.plan(1) const result = engine.render('no-data') assert.equal(result, 'hello world!') }) test('string-interpolation', assert => { assert.plan(1) const result = engine.render('with-data', { name: 'ahmad' }) assert.equal(result, 'hello ahmad') }) test('string-interpolation missing data', assert => { assert.plan(1) const result = engine.render('with-data') assert.equal(result, 'hello undefined') }) test('front-matter data', assert => { assert.plan(1) const result = engine.render('front-matter') assert.equal(result, 'hello ahmad') }) test('front-matter data override', assert => { assert.plan(1) const result = engine.render('front-matter', { name: 'nicole' }) assert.equal(result, 'hello nicole') }) src/ui/user/UserDetailsModal.js0 // @flow import React, { PureComponent as Component } from "react"; import localeString from "locale-string"; import get from "lodash.get"; import { A, Button, Spinner, RichContent, Modal } from "../common"; import UserName from "./UserName"; import UserAvatar from "./UserAvatar"; import UserDetailsEditForm from "./UserDetailsEditForm"; import GameSummaryList from "../game/GameSummaryList"; import UserRankGraph from "./UserRankGraph"; import { getUserStatusText, getUserAuthName } from "../../model/user"; import { isAncestor } from "../../util/dom"; import { formatLocaleDate, timeAgo } from "../../util/date"; import { InvariantError } from "../../util/error"; import type { UserDetailsRequest, User, UserDetails, GameSummary, RankGraph, Index, AppActions, } from "../../model"; const MAX_GAME_SUMMARIES = 500; type Props = { currentUser: ?User, userDetailsRequest: ?UserDetailsRequest, usersByName: Index, rankGraphsByChannelId: Index, gameSummariesByUser: Index>, actions: AppActions, }; type State = { tab: "bio" | "games" | "rankGraph", editing: boolean, }; export default class UserDetailsModal extends Component { state = { tab: "bio", editing: false, }; _mainDiv: ?HTMLElement; componentDidMount() { document.addEventListener("keyup", this._onKeyUp); if (document.body) { document.body.classList.add("no-scroll"); } } componentWillUnmount() { document.removeEventListener("keyup", this._onKeyUp); if (document.body) { document.body.classList.remove("no-scroll"); } } render() { let { currentUser, userDetailsRequest, usersByName, gameSummariesByUser, rankGraphsByChannelId, actions, } = this.props; if (!currentUser || !userDetailsRequest) { throw new InvariantError("currentUser and userDetailsRequest required"); } let { tab, editing } = this.state; let content; let offline; let user = usersByName[userDetailsRequest.name]; let gameSummaries = gameSummariesByUser[userDetailsRequest.name]; let details = user && user.details; let channelId = details && details.channelId; if (editing && user && user.details && details) { return ( ); } if (user) { offline = user.flags && !user.flags.connected; if (details) { let persName = details.personalName && details.personalName !== user.name ? details.personalName : null; let authName = getUserAuthName(user); let locale: Object = localeString.parse( details.locale.replace("_", "-") ); let joinedDate = new Date(details.regStartDate); let bio = details.personalInfo ? details.personalInfo.trim() : ""; if (this.state.tab === "bio" && !bio) { tab = "games"; } content = (
{persName ? (
{persName}
) : null} {authName ? (
{authName}
) : null}
Joined {formatLocaleDate(joinedDate)}
{locale ? (
{locale.language} /{" "} {locale.country.replace("United States", "US")}
) : null} {details.email && !details.privateEmail ? ( ) : null}
{bio || gameSummaries ? (
{bio ? ( Bio ) : null} {gameSummaries ? ( {gameSummaries.length} Games ) : null} Rank
{bio && tab === "bio" ? (
) : null} {gameSummaries && gameSummaries.length && tab === "games" ? (
) : null} {tab === "rankGraph" ? (
) : null}
) : null}
); } else { content = (
); } } else if (userDetailsRequest.status === "pending") { content = (
); } else { content = (
User not found
); } let userDetailsModalMessage = (
); return (
×
{user ? getUserStatusText(user) + (offline && user.details ? " - last on " + timeAgo(new Date(user.details.lastOn)) : "") : null}
{user ? (
{user && (user.name !== currentUser.name && user.flags && user.flags.connected) ? ( userDetailsModalMessage ) : user && user.name === currentUser.name ? (
) : null}
) : null}
{user ? ( ) : ( userDetailsRequest.name )}
{content}
); } _setMainRef = (ref: HTMLElement | null) => { this._mainDiv = ref; }; _onKeyUp = (e: Object) => { if (e.key === "Escape" || e.keyCode === 27) { this.props.actions.onCloseUserDetail(); } }; _onMaybeClose = (e: Object) => { let insideModal = this._mainDiv && (e.target === this._mainDiv || isAncestor(e.target, this._mainDiv)); if (insideModal) { return; } this.props.actions.onCloseUserDetail(); }; _onShowBio = () => { this.setState({ tab: "bio" }); }; _onShowGames = () => { this.setState({ tab: "games" }); }; _onShowRankGraph = () => { const { actions, userDetailsRequest, usersByName } = this.props; const user = userDetailsRequest && usersByName[userDetailsRequest.name]; const channelId: number = Number( user && user.details && user.details.channelId ); actions.onRequestRankGraph(channelId); this.setState({ tab: "rankGraph" }); }; _onSelectGame = (game: GameSummary) => { this.props.actions.onCloseUserDetail(); if (game.inPlay) { this.props.actions.onJoinGame(game.timestamp); } else { this.props.actions.onLoadGame(game.timestamp); } }; _onStartChat = () => { let { userDetailsRequest, usersByName } = this.props; if (userDetailsRequest) { let user = usersByName[userDetailsRequest.name]; if (user) { this.props.actions.onStartChat(user); } } }; _onEdit = () => { this.setState({ editing: true }); }; _onDoneEditing = () => { this.setState({ editing: false }); }; _onSaveUserDetails = ( user: User, details: UserDetails, newPassword: string ) => { this.props.actions.onUpdateProfileDetails(user, details); if (newPassword) { this.props.actions.onUpdatePassword(user, newPassword); } this._onDoneEditing(); }; } matrixRain() { const c = this.refs.c; const ctx = this.refs.c.getContext("2d"); c.height = window.innerHeight; c.width = window.innerWidth; let eggtronic = 'EggTronicYangEggTronicXu'; eggtronic = eggtronic.split(""); let font_size = 10; let columns = c.width / font_size; //number of columns for rain let drops = []; //x below is the x coordinate //1 - y co-cordinate of the drop - same for every drop initially for (let x = 0; x < columns; x++) drops[x] = 1; function draw() { //black BG for canvas //translucent BG to show trail ctx.fillStyle = "rgba(0, 0, 0, 0.05)"; ctx.fillRect(0, 0, c.width, c.height); ctx.fillStyle = "#0f0"; ctx.font = font_size / 1.5 + "px arial"; //looping over drops for (let i = 0; i < drops.length; i++) { let text = eggtronic[Math.floor(Math.random() * eggtronic.length)]; ctx.fillText(text, i * font_size, drops[i] * font_size); if (drops[i] * font_size > c.height && Math.random() > 0.975) drops[i] = 0; drops[i]++ } } setInterval(draw, 33); } import _extends from "@babel/runtime-corejs2/helpers/esm/extends"; import React from "react"; import PropTypes from "prop-types"; function URLWidget(props) { var BaseInput = props.registry.widgets.BaseInput; return React.createElement(BaseInput, _extends({ type: "url" }, props)); } if (process.env.NODE_ENV !== "production") { URLWidget.propTypes = { value: PropTypes.string }; } export default URLWidget;az67128/create-react-app 'use strict'; const fs = require('fs-extra'); const union = require('lodash/union'); const cssFileRegexp = /\.css$/; const importLineRegexp = /@import .*$/gm; const foldersToIgnoreMergeCssRegexp = [ /^src[\/\\]businessObjects.*\.css$/, /^src[\/\\]componentLibraries.*\.css$/, /^src[\/\\]layouts.*\.css$/, ]; module.exports = (fromPath, toPath) => { if ( cssFileRegexp.test(fromPath) && cssFileRegexp.test(toPath) && fs.existsSync(toPath) && !foldersToIgnoreMergeCssRegexp.some(f => f.test(fromPath)) ) { const originalPath = toPath.replace(cssFileRegexp, '.original.css'); if (!fs.existsSync(originalPath)) { fs.copySync(toPath, originalPath); } const fromFile = fs.readFileSync(fromPath, 'utf8'); const toFile = fs.readFileSync(originalPath, 'utf8'); const fromImports = fromFile.match(importLineRegexp); const toImports = toFile.match(importLineRegexp); const imports = union(fromImports, toImports); const resultFile = ` ${(imports || []).join('\n')} ${toFile.replace(importLineRegexp, '')} ${fromFile.replace(importLineRegexp, '')} `; fs.writeFileSync(toPath, resultFile); } else { fs.copySync(fromPath, toPath); } }; import React, { useState, useEffect } from 'react' import { useDispatch } from 'react-redux' import { Base64 } from "js-base64"; import { Editor } from '@tinymce/tinymce-react'; import { Paper, Typography, Grow, makeStyles, TextField, IconButton, Button, Box, Toolbar } from '@material-ui/core' import Skeleton from '@material-ui/lab/Skeleton' import ArrowBackIos from '@material-ui/icons/ArrowBackIos' import { getTemplate } from '../../service/templateServices'; import { sendMessage } from '../../service/messageServices'; import { setAlertAction } from '../../state/app/appDucks'; const useStyles = makeStyles(theme => ({ root: { width: '100%', borderRadius: '10px' }, editorBox: { height: '100%', width: '100%' }, title: { flexGrow: 1, display: 'flex', alignItems: 'center' }, morebutton: { padding: 0 }, divider: { backgroundColor: theme.palette.secondary.main, margin: "0 8px", height: '20px' }, buttonDiv: { display: 'flex', '& > *': { marginLeft: theme.spacing(1), } }, contentDiv: { padding: '0 24px', height: 'calc(100% - 64px)' }, textDiv: { marginBottom: theme.spacing(4) } })) const New = ({ history, location }) => { const classes = useStyles(); const dispatch = useDispatch(); const [loading, setLoading] = useState(true); const [templateHtml, setTemplateHtml] = useState(null) const [form, setForm] = useState({ to: null, cc: '', subject: null, message: null }) useEffect(() => { const loadTemplate = (templateId) => { getTemplate(templateId) .then(resp => { setTemplateHtml(resp.dataHtml) }) } loadTemplate(location.state) return }, [location.state]) const handleSubmit = (e) => { e.preventDefault(); const emailTo = form.to; const ccTo = form.cc; const subject = form.subject; const message = form.message; formatMessage( { To: emailTo, CC: ccTo, Subject: subject, 'Content-Type': 'text/html; charset=UTF-8', "Content-Transfer-Encoding": "base64" }, message ); }; const formatMessage = (headers_obj, message) => { let email = ""; for (var header in headers_obj) { email += header += ": " + headers_obj[header] + "\r\n"; } email += "\r\n" + message; const base64EncodedEmail = Base64.encodeURI(email); sendMessage(base64EncodedEmail) .then(resp => { if (resp.status === 200) { dispatch(setAlertAction({ type: 'success', message: 'Message has been sent!' })) history.push({ pathname: '/message', }); } }) .catch(error => { dispatch(setAlertAction({ type: 'error', message: error.result.error.message })) }) }; const handleEditorOnChange = (content) => { setForm(prevState => ({ ...prevState, message: content })) } const handleFormOnChange = (event) => { const { name, value } = event.target; setForm(prevState => ({ ...prevState, [name]: value })) } return ( history.push('/library')} className={classes.button} size='small'> {!loading ? 'Send Message' : }
{!loading && }
{!loading ? <> : }
) } export default New proGian/shorturl 'use strict'; var gulp = require('gulp'); var plugins = require('gulp-load-plugins')(); gulp.task('copygentelella', function () { var g_folders = ['build', 'vendors']; g_folders.forEach(function (folder) { gulp.src(['./node_modules/gentelella/' + folder + '/**/*.*']) .pipe(gulp.dest('./public/vendors/gentelella/' + folder)); }); }); gulp.task('build-dev', function () { gulp.src(['./libs/gentelella/vendors/bootstrap/dist/css/bootstrap.css', './less/main.less']) .pipe(plugins.less()) .pipe(plugins.rename('main.css')) .pipe(gulp.dest('./public/css')); }); gulp.task('stylewatch', function () { gulp.watch(['./less/**/*.less'], ['build-dev']); }); gulp.task('default', ['copygentelella', 'build-dev', 'stylewatch']); /*slideshow*/ const slideShoDiv = () => { for (let i = 1; i < 5; i++) { const div = document.createElement("div"); div.style.backgroundImage = `url(img/images/slideshow/section-1-bg-${i}.jpg)` i === 1 && div.classList.add("change") document.querySelector(".slideshow").appendChild(div); } } slideShoDiv(); $(document).ready(function () { const divs = $(".slideshow div"); a = 1; setInterval(() => { a++; const div = $(".slideshow .change"); div.removeClass("change"); if (a < divs.length) { div.next().addClass("change"); } else { a = 1; divs.first().addClass("change") } }, 10000) /*cubbe controller*/ let x = 0; let y = 0; let z = 0; let boolean = true; let inteval; const cube = $(".cube"); $(".top-x-control").click(() => { cube.css("transform", `rotateX(${x += 20}deg) rotateY(${y}deg) rotateZ(${z}deg)`); }); $(".bottom-x-control").click(() => { cube.css("transform", `rotateX(${x -= 20}deg) rotateY(${y}deg) rotateZ(${z}deg)`); }); $(".left-y-control").click(() => { cube.css("transform", `rotateX(${x}deg) rotateY(${y -= 20}deg) rotateZ(${z}deg)`); }); $(".right-y-control").click(() => { cube.css("transform", `rotateX(${x}deg) rotateY(${y += 20}deg) rotateZ(${z}deg)`); }); $(".top-z-control").click(() => { cube.css("transform", `rotateX(${x}deg) rotateY(${y}deg) rotateZ(${z -= 20}deg)`); }); $(".bottom-z-control").click(() => { cube.css("transform", `rotateX(${x}deg) rotateY(${y}deg) rotateZ(${z += 20}deg)`); }); $(".controls").mouseover(() => { clearInterval(inteval); }) $(".controls").mouseout(() => { inteval = setInterval(() => { cube.css("transform", `rotateX(${x}deg) rotateY(${y += 2}deg) rotateZ(${z}deg)`); }, 100) }) if (boolean) { inteval = setInterval(() => { cube.css("transform", `rotateX(${x}deg) rotateY(${y += 2}deg) rotateZ(${z}deg)`); }, 100) } else { clearInterval(inteval); } /*end cube controller*/ /*e*/ }); /* end of slideshow*/ /*controllers*/ migroose/dataRemover/index.js var RSVP = require("rsvp"); var _ = require("underscore"); var mongoose = require("mongoose"); // Data Remover // ------------ function DataRemover(collectionConfig){ this.collectionConfig = collectionConfig; } // Instance Methods // ---------------- DataRemover.prototype.remove = function(cb){ var that = this; var promises = []; for (var name in this.collectionConfig) { if (this.collectionConfig.hasOwnProperty(name)){ var config = this.collectionConfig[name]; var promise = that.removeCollection(name, config); promises.push(promise); } } RSVP.all(promises) .then(function(data){ cb(undefined); }) .catch(function(err){ cb(err); }); }; DataRemover.prototype.removeCollection = function(name, collectionConfig){ var that = this; var collectionName, query; if (_.isObject(collectionConfig)){ query = collectionConfig.query; collectionName = collectionConfig.collection; } else { query = {}; collectionName = collectionConfig; } return _executeQuery(collectionName, query); }; // Helpers // ------- function _executeQuery(collectionName, query){ return new RSVP.Promise(function(resolve, reject){ mongoose.connection.db.collection(collectionName, function(err, collection){ if (err) { return reject(err); } collection.remove(query, function(err, data){ if (err) { return reject(err); } resolve(); }); }); }); } // Exports // ------- module.exports = DataRemover; public/js/ScalaDNS/visual/widget/DomainRecordForm.js var ScalaDNS = ScalaDNS || {}; (function() { ScalaDNS.DomainRecordForm = function(container) { ScalaDNS.DomainRecordForm.parent.constructor.call(this, 'DomainRecordForm', container); this.domain = null; this.record = null; this._validator = null; this._status = { blocked: false, type: null, ipv4_policy: null, ipv6_policy: null, ns_policy: null, selected_ips: {} } } ScalaDNS.extend(ScalaDNS.DomainRecordForm, ScalaDNS.BaseWidget); ScalaDNS.DomainRecordForm.prototype.load = function(settings, callback) { var that = this; ScalaDNS.DomainService.loadDomains(function() { that.domain = ScalaDNS.fullDomains.get(settings.domain); callback(); }); } ScalaDNS.DomainRecordForm.prototype.init = function() { if(this.domain === null) return; var that = this, ipWeightSwitch; this._tpl = $('#setsFormTemplate').clone().removeAttr('id').removeClass('hidden'); this._weighted_ipv4_tpl = $('[data-name="a"] [data-type="rout-weight"] .control-group', this._tpl).clone(); this._weighted_ipv6_tpl = $('[data-name="aaaa"] [data-type="rout-weight"] .control-group', this._tpl).clone(); this._weighted_ns_tpl = $('[data-name="ns"] [data-type="rout-weight"] .control-group', this._tpl).clone(); this._validator = this.initValidator(); this.form = this.initFormFunctions(); this.updateFormStatus(); $(':fname(name)', this._tpl).bind('keydown', function(evt) { if(that._status.blocked === true) { evt.preventDefault(); } }); $('[name="typ"]', this._tpl).bind('change', function(evt) { if(that._status.blocked === true) { $('option', this).removeAttr('selected'); $('option[value="' + that._status.type + '"]', this).attr('selected', true); } else { that._status.type = $(this).val(); that.switchFormPart($(this).val().toLowerCase()); } }); $('[data-id="add-record"]', this._tpl).bind('click', function(evt) { ScalaDNS.AlertBox.clear(); if(that._status.blocked === false) { var typ = $('[name="typ"]', this._tpl).val(), formPart = $('[data-type="rr-content"]:visible'), domain = jQuery.extend(true, {}, that.domain), validateHead, validateBody, record; evt.preventDefault(); switch(typ) { case 'A': validateHead = that._validator.name.validate(); if($('[data-id="ipv4_routing_simple"]').prop('checked')) { validateBody = that._validator[typ + 'Simple'].validate(); } else { validateBody = that._validator[typ + 'Weighted'].validate(); } break; case 'AAAA': validateHead = that._validator.name.validate(); if($('[data-id="ipv6_routing_simple"]').prop('checked')) { validateBody = that._validator[typ + 'Simple'].validate(); } else { validateBody = that._validator[typ + 'Weighted'].validate(); } break; case 'NS': validateHead = that._validator.name.validate(); if($('[data-id="ns_routing_simple"]').prop('checked')) { validateBody = that._validator[typ + 'Simple'].validate(); } else { validateBody = that._validator[typ + 'Weighted'].validate(); } break; case 'CNAME': validateHead = that._validator.simpleName.validate(); validateBody = that._validator[typ].validate(); break; default: validateHead = that._validator.name.validate(); validateBody = that._validator[typ].validate(); break; } if(validateHead.valid && validateBody.valid) { newRecord = that.form[typ].parse(formPart); if(that.record !== null && that.record.typ === typ) { domain[that.record.typ].splice(that.record.id, 1, newRecord); } else { if(that.record !== null) { domain[that.record.typ].splice(that.record.id, 1); } domain[typ] = domain[typ] || []; domain[typ].push(newRecord); } if(domain.SOA && domain.NS && (domain.NS.length > 1 || domain.NS[0].value.length > 1)) { ScalaDNS.DomainService.saveDomain(domain, function(result) { if(result.code < 2) { ScalaDNS.onRecordsUpdate.raise(new ScalaDNS.UpdatedEvent(this, {})); that.record = null; that.domain = result.data[0]; that.clearForm(); if(result.code > 0) { ScalaDNS.AlertBox.showClear('

Warning!

' + result.messages.join('
')); } if(result.data.length > 1) { ScalaDNS.AlertBox.showClear('Warning! The domains have been reorganized.'); } } else { ScalaDNS.AlertBox.showClear(result.messages.join('
'), 'error'); } }); } else { that.domain = domain; ScalaDNS.fullDomains.set(that.domain.origin, that.domain); that.clearForm(); ScalaDNS.AlertBox.showClear('Warning! The domain could not be saved at this point because it does not contain all the required records. Make sure you add a SOA record and at least 2 NS records.'); ScalaDNS.onRecordsUpdate.raise(new ScalaDNS.UpdatedEvent(this, {})); } } } }); $('[data-id="cancel"]', this._tpl).bind('click', function(evt) { that.clearForm(); that.updateFormStatus(); that.record = null; }); this._tpl.delegate('[data-name="a"] [data-type="add"]', 'click', function() { if(that._status.blocked === false) { that.ipAddRow(this, that._weighted_ipv4_tpl.clone()); } }); this._tpl.delegate('[data-name="aaaa"] [data-type="add"]', 'click', function() { if(that._status.blocked === false) { that.ipAddRow(this, that._weighted_ipv6_tpl.clone()); } }); this._tpl.delegate('[data-name="ns"] [data-type="add"]', 'click', function() { if(that._status.blocked === false) { that.ipAddRow(this, that._weighted_ns_tpl.clone()); } }); this._tpl.delegate('[data-type="remove"]', 'click', function() { var typ = $(':fname(typ)', that._tpl).val(); $(this).closest('.control-group').remove(); that._status.blocked = false; that._validator[typ + 'WeightedDuplicity'].validate(); }); this._tpl.delegate('[name="ipv4_routing"]', 'click', function(evt) { if(that._status.blocked === false) { that._status.ipv4_policy = $(this).attr('data-id'); that.ipWeightSwitch(this, 'a', 'ipv4', that._weighted_ipv4_tpl.clone()); } else { evt.preventDefault(); $('[data-id="' + that._status.ipv4_policy + '"]').prop('checked', true); } }); this._tpl.delegate('[name="ipv6_routing"]', 'click', function(evt) { if(that._status.blocked === false) { that._status.ipv6_policy = $(this).attr('data-id'); that.ipWeightSwitch(this, 'aaaa', 'ipv6', that._weighted_ipv6_tpl.clone()); } else { evt.preventDefault(); $('[data-id="' + that._status.ipv6_policy + '"]').prop('checked', true); } }); this._tpl.delegate('[name="ns_routing"]', 'click', function(evt) { if(that._status.blocked === false) { that._status.ns_policy = $(this).attr('data-id'); that.ipWeightSwitch(this, 'ns', 'ns', that._weighted_ns_tpl.clone()); } else { evt.preventDefault(); $('[data-id="' + that._status.ns_policy + '"]').prop('checked', true); } }); this._tpl.delegate('.control-group input[type="text"], .control-group textarea', 'keyup', function() { that._onValidate(this); }); this._tpl.delegate('[name="ipv4_address[]"]', 'keyup', function() { that._status.blocked = false; that._validator.AWeightedDuplicity.validate(); }); this._tpl.delegate('[name="ipv4_value"]', 'keyup', function() { that._status.blocked = false; that._validator.ASimpleDuplicity.validate(); }); this._tpl.delegate('[name="ipv6_address[]"]', 'keyup', function() { that._status.blocked = false; that._validator.AAAAWeightedDuplicity.validate(); }); this._tpl.delegate('[name="ipv6_value"]', 'keyup', function() { that._status.blocked = false; that._validator.AAAASimpleDuplicity.validate(); }); this._tpl.delegate('[name="ns_hostname[]"]', 'keyup', function() { that._status.blocked = false; that._validator.NSWeightedDuplicity.validate(); }); this._tpl.delegate('[name="ns_value"]', 'keyup', function() { that._status.blocked = false; that._validator.NSSimpleDuplicity.validate(); }); this._tpl.bind('click', function(evt) { evt.stopPropagation(); }); this._tpl.delegate('[data-type="error-msg"] button', 'click', function() { $(this).closest('[data-type="error-msg"]').remove(); }); this._tpl.delegate('[data-toggle="buttons-radio"] button', 'click', function(evt) { var buttonGroup = $(this).closest('[data-toggle="buttons-radio"]'), parent = $(this).closest('.control-group'); $('button', buttonGroup).removeClass('active'); $(this).addClass('active'); $('input[type="text"]', parent).val($(this).text().toUpperCase()); }); $('input[type="text"]', $('[data-toggle="buttons-radio"]', this._tpl).closest('.control-group')).bind('keyup', function() { var parent = $(this).closest('.control-group'), value = $(this).val(); $('[data-toggle="buttons-radio"] button').removeClass('active'); if(value !== '') { $('[data-toggle="buttons-radio"] button', parent).filter(function() { return $(this).text() === value; }).addClass('active'); } }); ScalaDNS.onRecordSelect.bind(this, this.recordSelected); ScalaDNS.onDomainUpdate.bind(this, this.domainUpdated); } ScalaDNS.DomainRecordForm.prototype.draw = function() { if(this.domain !== null) { this.drawForm(); $('.row-fluid', this.container).append(this._tpl); } } ScalaDNS.DomainRecordForm.prototype.dispose = function() { $(':fname(name)', this._tpl).unbind(); $('[name="typ"]', this._tpl).unbind(); $('[data-id="add-record"]', this._tpl).unbind(); $('[data-id="cancel"]', this._tpl).unbind(); if(this._tpl) { this._tpl.unbind(); this._tpl.undelegate(); } ScalaDNS.onRecordSelect.unbind(this, this.recordSelected); ScalaDNS.onDomainUpdate.unbind(this, this.domainUpdated); } ScalaDNS.DomainRecordForm.prototype.drawForm = function() { this.clearForm(); $('[data-type="rr-content"]', this._tpl).hide(); $('[data-type="rout-weight"]', this._tpl).hide(); if(this.record === null) { $('[data-name="a"]', this._tpl).show(); } else { $('[data-type="form-title"]', this._tpl).text('Edit Record Set'); $('[data-id="add-record"]', this._tpl).text('Update Record Set'); this.drawFormPart(this.record.typ, this.record.data); } this.updateFormStatus(); } ScalaDNS.DomainRecordForm.prototype.clearForm = function(typ) { var form; this._status.blocked = false; if(!typ) { form = this._tpl; $('[data-type="form-title"]', this._tpl).text('Create Record Set'); $('[data-id="add-record"]', this._tpl).text('Create Record Set'); } else { form = $('[data-name="' + typ.toLowerCase() + '"]', this._tpl); } $('input[type="text"]', form).val(''); $('input[type="hidden"]', form).val(''); $('textarea', form).val(''); $('[name="ipv4_routing"]', form).prop('checked', false); $('[name="ipv4_routing"]:first', form).prop('checked', true); $('[name="ipv6_routing"]', form).prop('checked', false); $('[name="ipv6_routing"]:first', form).prop('checked', true); $('[data-name="a"] [data-type="rout-weighted .control-group"]', form).remove(); $('[data-name="a"] [data-type="rout-weighted"]', form).append(this._weighted_ipv4_tpl); $('[data-name="aaaa"] [data-type="rout-weighted .control-group"]', form).remove(); $('[data-name="aaaa"] [data-type="rout-weighted"]', form).append(this._weighted_ipv6_tpl); $('[data-type="rout-simple"]', form).show(); $('[data-type="rout-weight"]', form).hide(); $('.control-group', form).removeClass('error'); $('.help-inline', form).remove(); $('[data-toggle="buttons-radio"] button', form).removeClass('active'); ScalaDNS.AlertBox.clear(); this.refreshNameValidator(); } ScalaDNS.DomainRecordForm.prototype.drawFormPart = function(typ, data) { var formPart = $('[data-name="' + typ.toLowerCase() + '"]', this._tpl); $('[name="name"]', this._tpl).val(data.name); $('[name="typ"] option', this._tpl).removeAttr('selected'); $('[name="typ"] option[value="' + typ + '"]', this._tpl).attr('selected', 'selected'); this.form[typ].populate(data, formPart); formPart.show(); } ScalaDNS.DomainRecordForm.prototype.switchFormPart = function(typ) { $('[data-type="rr-content"]', this._tpl).hide(); $('[data-name="' + typ + '"]', this._tpl).show(); this.refreshNameValidator(); } ScalaDNS.DomainRecordForm.prototype.isWeighted = function(data) { if(jQuery.isArray(data)) { var i = 0, weighted = false; while(i < data.length && weighted === false) { weighted = this.isWeighted(data[i]); i++; } return weighted; } else if(jQuery.isPlainObject(data)) { return data.weight && data.weight > 1; } else { return false; } } ScalaDNS.DomainRecordForm.prototype.initFormFunctions = function() { var that = this, populateWeighted = function(row_tpl, id) { return function(data, container) { $(':dtype(rout-weight) .control-group', container).remove(); $(':dtype(single-value)', container).empty(); $(':dtype(routing-policy)', container).removeAttr('checked'); foreach(data.value, function(item, index) { row = row_tpl.clone(); if(index === 0) { $('button', row).attr('data-type', 'add'); } else { $('button', row).attr('data-type', 'remove'); $('button i', row).removeClass('icon-plus'); $('button i', row).addClass('icon-minus'); $(':dtype(single-value)', container).val($(':dtype(single-value)', container).val() + '\n'); } $(':dtype(wv-weight)', row).val(item.weight); $(':dtype(wv-value)', row).val(item[id]); $(':dtype(rout-weight)', container).append(row); $(':dtype(single-value)', container).val($(':dtype(single-value)', container).val() + item[id]); }); if(that.isWeighted(data.value)) { $(':dname(routing-weighted)', container).prop('checked', true); $(':dtype(rout-simple)', container).hide(); $(':dtype(rout-weight)', container).show(); } else { $(':dname(routing-simple)', container).prop('checked', true); $(':dtype(rout-weight)', container).hide(); $(':dtype(rout-simple)', container).show(); } } }, populateText = function(data, container) { $(':dtype(text-value)', container).val(data.value); }, populateMx = function(data, container) { $(':dtype(text-param)', container).val(data.priority); $(':dtype(text-value)', container).val(data.value); }, populateSoa = function(data, container) { $(':fname(soa_serial)', container).val(data.serial); $(':fname(soa_mname)', container).val(data.mname); $(':fname(soa_rname)', container).val(data.rname); $(':fname(soa_ttl)', container).val(data.at); $(':fname(soa_refresh)', container).val(data.refresh); $(':fname(soa_retry)', container).val(data.retry); $(':fname(soa_expire)', container).val(data.expire); $(':fname(soa_minimum)', container).val(data.minimum); $('input[type="text"]', $('[data-toggle="buttons-radio"]', that._tpl).closest('.control-group')).each(function() { var parent = $(this).closest('.control-group'), value = $(this).val().toLowerCase(); $('[data-toggle="buttons-radio"] button', parent).removeClass('active'); $('[data-toggle="buttons-radio"] button', parent).filter(function() { return $(this).text() === value }).addClass('active'); }); }, populateMText = function(data, container) { foreach(data.value, function(item, index) { if(index > 0) { $(':dtype(text-values)', container).append('\n'); } $(':dtype(text-values)', container).append(item); }); }, parseWeighted = function(callback) { return function(container) { var json, value = [], weight = 1, typ = container.attr('data-name'); json = { name: $(':fname(name)', that._tpl).val(), 'class': 'in' }; if($(':dname(routing-simple)', container).is(':checked')) { foreach($(':dtype(single-value)', container).val().split('\n'), function(item) { if(item !== '') { value.push(callback(weight, item)); } }); } else { $(':dtype(rout-weight) .control-group', container).each(function() { if($(':dtype(wv-value)', this).val() !== '') { if($(':dtype(wv-weight)', this).val() != '') { weight = $(':dtype(wv-weight)', this).val(); } value.push(callback(weight, $(':dtype(wv-value)', this).val())); } }); } json.value = value; return json; } }, parseText = function(container) { return { name: $(':fname(name)', that._tpl).val(), 'class': 'in', value: $(':dtype(text-value)', container).val() } }, parseMx = function(container) { return { name: $(':fname(name)', that._tpl).val(), 'class': 'in', priority: $(':dtype(text-param)', container).val(), value: $(':dtype(text-value)', container).val() } }, parseSoa = function(container) { return { name: $(':fname(name)', that._tpl).val(), at: $(':fname(soa_ttl)', that._tpl).val(), 'class': 'in', mname: $(':fname(soa_mname)', container).val(), rname: $(':fname(soa_rname)', container).val(), serial: $(':fname(soa_serial)', container).val(), refresh: $(':fname(soa_refresh)', container).val(), retry: $(':fname(soa_retry)', container).val(), expire: $(':fname(soa_expire)', container).val(), minimum: $(':fname(soa_minimum)', container).val() } }, parseMText = function(container) { var json, value = []; json = { name: $(':fname(name)', that._tpl).val(), 'class': 'in' }; foreach($(':dtype(text-values)', container).val().split('\n'), function(item) { value.push(item); }); json.value = value; return json; }; return { 'A': { populate: populateWeighted(that._weighted_ipv4_tpl, 'ip'), parse: parseWeighted(function(weight, address) {return {weight: weight, ip: address};}) }, 'AAAA': { populate: populateWeighted(that._weighted_ipv6_tpl, 'ip'), parse: parseWeighted(function(weight, address) {return {weight: weight, ip: address};}) }, 'CNAME': { populate: populateText, parse: parseText }, 'MX': { populate: populateMx, parse: parseMx }, 'NS': { populate: populateWeighted(that._weighted_ns_tpl, 'ns'), parse: parseWeighted(function(weight, hostname) {return {weight: weight, ns: hostname};}) }, 'PTR': { populate: populateText, parse: parseText }, 'SOA': { populate: populateSoa, parse: parseSoa }, 'TXT': { populate: populateMText, parse: parseMText } } } ScalaDNS.DomainRecordForm.prototype.ipAddRow = function(target, template) { var parent = $(target).closest('.control-group'); $('input[type="text"]', template).val(''); $('button', template).attr('data-type', 'add'); $(target).attr('data-type', 'remove'); $('i', target).removeClass('icon-plus'); $('i', target).addClass('icon-minus'); parent.before(template); } ScalaDNS.DomainRecordForm.prototype.ipWeightSwitch = function(target, typ, prefix, template) { var parent = $(target).parent().closest('[data-name]'), cont_simple = $('[data-type="rout-simple"]', parent), cont_weight = $('[data-type="rout-weight"]', parent), //textarea = $('[name="' + prefix + '_value"]', parent), textarea = $(':dtype(single-value)', parent), that = this, tpl; if($(target).val() === 'weighted') { if(!$('[data-type="rout-weight"]', parent).is(':visible')) { var data = textarea.val().split('\n'); $('.control-group', cont_weight).remove(); if(data.length == 0) { cont_weight.append(template); } else { var unique_ips = {}; foreach(data, function(item, index) { if(unique_ips[item] === undefined) { unique_ips[item] = item; tpl = template.clone(); if(that._status.selected_ips[item]) { $(':dtype(wv-weight)', tpl).val(that._status.selected_ips[item]); } else { $(':dtype(wv-weight)', tpl).val(''); } $(':dtype(wv-value)', tpl).val(item); if(index == 0) { $('button', tpl).attr('data-type', 'add'); } else { $('button', tpl).attr('data-type', 'remove'); $('button i', tpl).removeClass('icon-plus'); $('button i', tpl).addClass('icon-minus'); } cont_weight.append(tpl); } }); } cont_simple.hide(); cont_weight.show(); } } else { if(!$('[data-type="rout-simple"]', parent).is(':visible')) { var value; this._status.selected_ips = {}; textarea.val(''); $('[data-type="rout-weight"] .control-group', parent).each(function() { value = $(':dtype(wv-value)', this).val(); if(value != '' && that._status.selected_ips[value] === undefined) { that._status.selected_ips[value] = $(':dtype(wv-weight)', this).val(); if(textarea.val().indexOf(value) < 0) { if(textarea.val() != '') { textarea.val(textarea.val() + '\n'); } textarea.val(textarea.val() + value); } } }); cont_weight.hide(); cont_simple.show(); } } } ScalaDNS.DomainRecordForm.prototype.updateFormStatus = function() { this._status = { blocked: this._status.blocked, type: $(':fname(typ)', this._tpl).val(), ipv4_policy: $(':fname(ipv4_routing):checked').attr('data-id'), ipv6_policy: $(':fname(ipv6_routing):checked').attr('data-id'), selected_ips: {} } } ScalaDNS.DomainRecordForm.prototype.recordSelected = function(e) { this.record = e.obj; this.drawForm(); } ScalaDNS.DomainRecordForm.prototype.initValidator = function() { var form = $('form', this._tpl), that = this, callback, duplicityCallback; callback = this._onValidate; duplicityCallback = function(item, message) { that._onValidate(item, message); that._status.blocked = that._status.blocked || message !== undefined; } return { name: that._initNameValidation(form, callback), simpleName: that._initSimpleNameValidation(form, callback), ASimpleDuplicity: that._initASimpleDuplicityValidation(form, duplicityCallback), AWeightedDuplicity: that._initAWeightedDuplicityValidation(form, duplicityCallback), ASimple: that._initASimpleValidation(form, callback), AWeighted: that._initAWeightedValidation(form, callback), AAAASimpleDuplicity: that._initAAAASimpleDuplicityValidation(form, duplicityCallback), AAAAWeightedDuplicity: that._initAAAAWeightedDuplicityValidation(form, duplicityCallback), AAAASimple: that._initAAAASimpleValidation(form, callback), AAAAWeighted: that._initAAAAWeightedValidation(form, callback), CNAME: that._initCNAMEValidation(form, callback), MX: that._initMXValidation(form, callback), NSSimpleDuplicity: that._initNSSimpleDuplicityValidation(form, duplicityCallback), NSWeightedDuplicity: that._initNSWeightedDuplicityValidation(form, duplicityCallback), NSSimple: that._initNSSimpleValidation(form, callback), NSWeighted: that._initNSWeightedValidation(form, callback), PTR: that._initPTRValidation(form, callback), SOA: that._initSOAValidation(form, callback), TXT: that._initTXTValidation(form, callback) } } ScalaDNS.DomainRecordForm.prototype.refreshNameValidator = function() { var validator = this._validator.name; this._validator.name = this._initNameValidation(validator.form, validator.callback); } ScalaDNS.DomainRecordForm.prototype._onValidate = function(item, message) { var parent = $(item).closest('.control-group'), hlptext; if(message) { parent.addClass('error'); if($('span.help-inline', parent).length === 0) { hlptext = $('small', parent); if(hlptext.length === 0) { parent.append('' + message + ''); } else { hlptext.prev().before('' + message + ''); } } } else { if(parent.hasClass('error')) { $('span.help-inline', parent).remove(); parent.removeClass('error'); } } } ScalaDNS.DomainRecordForm.prototype._initSimpleNameValidation = function(form, callback) { return form.validateDNS({ rules: { name: { hostName: { relative: true, absolute: true } } }, messages: { name: { hostName: 'Not a valid host name' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initNameValidation = function(form, callback) { var exclude = []; if(this.record !== null) { exclude.push(this.record.data.name); } return form.validateDNS({ rules: { name: { hostName: { relative: true, absolute: true }, notEqualTo: { value: this._getRecordNames(), exclude: exclude } } }, messages: { name: { hostName: 'Not a valid host name', notEqualTo: 'The host name already exists' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initASimpleDuplicityValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv4_value': { uniqueInText: '\n' } }, messages: { 'ipv4_value': { uniqueInText: 'Duplicate IP address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initAWeightedDuplicityValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv4_address[]': { uniqueInGroup: true } }, messages: { 'ipv4_address[]': { uniqueInGroup: 'Duplicate IP address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initASimpleValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv4_value': { required: true, ipv4: { delimiter: '\n' } } }, messages: { 'ipv4_value': { required: 'No IP address specified', ipv4: 'Not a valid IP address', uniqueInGroup: 'Duplicate IP address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initAWeightedValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv4_address[]': { requiredGroup: true, ipv4: true } }, messages: { 'ipv4_address[]': { requiredGroup: 'No IP address specified', ipv4: 'Not a valid IP address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initAAAASimpleDuplicityValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv6_value': { uniqueInText: '\n' } }, messages: { 'ipv6_value': { uniqueInText: 'Duplicate IPv6 address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initAAAAWeightedDuplicityValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv6_address[]': { uniqueInGroup: true } }, messages: { 'ipv6_address[]': { uniqueInGroup: 'Duplicate IPv6 address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initAAAASimpleValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv6_value': { required: true, ipv6: { delimiter: '\n', uniqueInGroup: true } } }, messages: { 'ipv6_value': { required: 'No IP address specified', ipv6: 'Not a valid IPv6 address', uniqueInGroup: 'Duplicate IPv6 address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initAAAAWeightedValidation = function(form, callback) { return form.validateDNS({ rules: { 'ipv6_address[]': { requiredGroup: true, ipv6: true } }, messages: { 'ipv6_address[]': { requiredGroup: 'No IP address specified', ipv6: 'Not a valid IPv6 address' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initCNAMEValidation = function(form, callback) { return form.validateDNS({ rules: { cname_value: { domainName: { absolute: true, relative: true }, notEqualToElem: 'name' } }, messages: { cname_value: { domainName: 'Not a valid domain name', notEqualToElem: 'Cname points to itself' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initMXValidation = function(form, callback) { return form.validateDNS({ rules: { mx_priority: { number: true }, mx_value: { domainName: { absolute: true, relative: true } } }, messages: { mx_priority: { number: 'Not a valid number' }, mx_value: { domainName: 'Not a valid domain name' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initNSSimpleDuplicityValidation = function(form, callback) { return form.validateDNS({ rules: { 'ns_value': { uniqueInText: '\n' } }, messages: { 'ns_value': { uniqueInText: 'Duplicate NS hostname' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initNSWeightedDuplicityValidation = function(form, callback) { return form.validateDNS({ rules: { 'ns_hostname[]': { uniqueInGroup: true } }, messages: { 'ns_hostname[]': { uniqueInGroup: 'Duplicate NS hostname' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initNSSimpleValidation = function(form, callback) { return form.validateDNS({ rules: { 'ns_value': { required: true, domainName: { absolute: true, relative: true } } }, messages: { 'ns_value': { required: 'No NS hostname specified', domainName: 'Not a valid domain name' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initNSWeightedValidation = function(form, callback) { return form.validateDNS({ rules: { 'ns_hostname[]': { requiredGroup: true, domainName: { absolute: true, relative: true } } }, messages: { 'ns_hostname[]': { requiredGroup: 'No IP address specified', domainName: 'Not a valid domain name' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initPTRValidation = function(form, callback) { return form.validateDNS({ rules: { ptr_value: { domainName: { absolute: true, relative: true } } }, messages: { ptr_value: { domainName: 'Not a valid domain name' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initSOAValidation = function(form, callback) { return form.validateDNS({ rules: { soa_mname: { domainName: { absolute: true, relative: true } }, soa_rname: { domainName: { absolute: true, relative: true } }, soa_ttl: { ttl: true }, soa_refresh: { ttl: true }, soa_retry: { ttl: true }, soa_expire: { ttl: true }, soa_minimum: { ttl: true } }, messages: { soa_mname: { domainName: 'Not a valid domain name' }, soa_rname: { domainName: 'Not a valid domain name' }, soa_ttl: { ttl: 'Not a valid time record' }, soa_refresh: { ttl: 'Not a valid time record' }, soa_retry: { ttl: 'Not a valid time record' }, soa_expire: { ttl: 'Not a valid time record' }, soa_minimum: { ttl: 'Not a valid time record' } }, callback: callback }); } ScalaDNS.DomainRecordForm.prototype._initTXTValidation = function(form, callback) { return form.validateDNS({ rules: { txt_value: { required: true } }, messages: { txt_value: { required: 'Text must not be empty' } }, callback: callback }) } ScalaDNS.DomainRecordForm.prototype._getRecordNames = function() { var typ, records, array = [], i; if(this.record !== null) { typ = this.record.typ; } else { typ = $(':fname(typ)', this._tpl).val(); } records = this.domain[typ] if(records) { for(i = 0; i < records.length; i++) { array.push(records[i].name); } } return array; } ScalaDNS.DomainRecordForm.prototype.domainUpdated = function(e) { this.domain = e.obj; this.refreshNameValidator(); } }());import * as co from 'colourz'; export default function Colors() { this.background = new co.shifter(co.Palette.CrocTooth) .lum(0.2).base(); this.background2 = new co.shifter(co.Palette.CrocTooth) .lum(0.4).base(); this.potBg = new co.shifter(co.Palette.SummerSky) .lum(0.2).base(); this.actions = { 'sblind': new co.shifter(co.Palette.Mandarin) .lum(0.44) .base(), 'bblind': new co.shifter(co.Palette.Mandarin) .lum(0.44) .base(), 'raise': new co.shifter(co.Palette.Mandarin) .lum(0.54) .base(), 'check': new co.shifter(co.Palette.SummerSky) .lum(0.44) .base(), 'call': new co.shifter(co.Palette.SummerSky) .lum(0.44) .base(), 'fold': new co.shifter(co.Palette.FluRed) .lum(0.44) .base(), 'allin': new co.shifter(co.Palette.Pumpkin) .lum(0.44) .base() }; } Vue.component('bslide', { props:{ title:String, label:String, image:String, color:{ type:String, default:"#FFF" }, bgcolor:{ type:String, default:"#888" }, height:{ type:Number, default:"300px" }, align:{ type:String, default:'left' }, active:{ type:Number, default:0 }, }, template: `
` })// waldon: // 讲原型链的时候可以顺带讲出,带$符号一般作为默认规范。 // 比如vue中非父子组件通信可能会用到的总线机制, // 还有Vue的一些插件,比如vuex和饿了么UI。 // 其实都有用到一些全局的api挂载到Vue的原型链上,例如饿了么UI中的一些全局的提示和弹窗,vuex中的commit和dispatch方法 // 测试: function User() {} User.prototype.getUserName = function () { console.log(`getUserName 执行`) } const user = new User() user.getUserName() $(document).ready(function(){ var table = $('#supplierTable').DataTable(); var urlCode = ''; var tempID = ''; $("#btnAddSupplier").click(function(){ // URL OF ADD $("#supplier_form").find('.has-error').removeClass("has-error"); $("#supplier_form").find('.has-success').removeClass("has-success"); $('#supplier_form').find('.form-control-feedback').remove(); document.getElementById("supplier_form").reset(); document.getElementById('supplier_form').action = "{{URL::to('/maintenance/supplier-add')}}"; urlCode = '/maintenance/supplier-add'; }); $("#btnEditSupplier").click(function(){ // CHANGE TABLE DATANAME $("#supplier_form").find('.has-error').removeClass("has-error"); $("#supplier_form").find('.has-success').removeClass("has-success"); $('#supplier_form').find('.form-control-feedback').remove() document.getElementById("supplier_form").reset(); var tblData = table.row('tr.active').data(); var id = tblData[0]; $.ajax({ url: '/maintenance/supplier-edit', type: 'POST', data: { supplier_id: id }, success: function(data) { // CHANGE ADD THIS DEPENDS ON INPUT FIELDS $('#supplierName').val(data[0].strSupplierName); $('#street').val(data[0].strSupStreet); $('#brgy').val(data[0].strSupBrgy); $('#city').val(data[0].strSupCity); $('#emailAdd').val(data[0].strSupEmail); $('#supplierDesc').val(data[0].strSupplierDesc); // URL OF EDIT tempID = data[0].strSupplierID; document.getElementById('supplier_form').action = "{{URL::to('/maintenance/supplier-update')}}"; urlCode = '/maintenance/supplier-update'; }, error: function(result) { alert('No ID found'); } }); }) $(document).on('submit', '#supplier_form', function(e){ table.column(0).visible(false); e.preventDefault(); $.ajax({ type: "GET", url: '/maintenance/supplier-max', success: function(data){ var current = new Date(); var today = current.getFullYear() + '-' + current.getMonth() + '-' + current.getDate() + ' ' + current.getHours() + ':' + current.getMinutes() + ':' + current.getSeconds(); $.ajax({ type: "POST", url: urlCode, data: { id:data, supplier_name: $('#supplierName').val(), supplier_street: $('#street').val(), supplier_brgy: $('#brgy').val(), supplier_city: $('#city').val(), supplier_email: $('#emailAdd').val(), supplier_desc: $('#supplierDesc').val(), created_at: today, supplier_id: tempID }, success: function(result) { console.log(result); if(urlCode == '/maintenance/supplier-update'){ table.rows('tr.active').remove().draw(); noty({ type: 'success', layout: 'bottomRight', timeout: 3000, text: '

Supplier successfully updated!

', }); }else{ noty({ type: 'success', layout: 'bottomRight', timeout: 3000, text: '

Supplier successfully added!

', }); } table.row.add([ result.strSupplierID, result.strSupplierName, result.strSupStreet+" "+result.strSupBrgy+","+result.strSupCity, result.strSupEmail, result.strSupplierDesc, ] ).draw(false); //reset form document.getElementById("supplier_form").reset(); $('#add_supplier_modal').modal('toggle'); $('#btnEditSupplier').hide() $('#btnDeleteSuppliers').hide() $('#btnAddSupplier').show() }, error: function(result){ $.ajax({ url: '/maintenance/supplier-status', type: 'POST', data: { supplier_name: $('#supplierName').val() }, success: function(data) { var errors = result.responseJSON; if(errors == undefined){ if(data[0].strStatus == 'Active'){ noty({ type: 'error', layout: 'bottomRight', timeout: 3000, text: '

Supplier already exist!

', }); } else if(data[0].strStatus == 'Inactive'){ $('#SupplierReactivateModal').modal(); } } } }); } }) }, error: function(data){ alert('ERROR IN MAX ID'); } }) }) $('#btnDeleteSupplier').click(function(){ var tblname = $('#supplierTable').DataTable(); var selected = tblname.rows('tr.active').data(); var selectedArr = []; for(var i = 0; i < selected.length; i++) { selectedArr[i] = selected[i][0]; } $.ajax({ type: "POST", url: "/maintenance/supplier-delete", data: { supplier_id: selectedArr }, success: function(result) { tblname.rows('tr.active').remove().draw(); $('#SupplierDeleteModal').modal('toggle'); $('#btnAddSupplier').show(); $('#btnEditSupplier').hide(); $('#btnDeleteSuppliers').hide(); noty({ type: 'error', layout: 'bottomRight', timeout: 3000, text: '

Supplier(s) successfully deactivated!

', }); }, error: function(result) { alert('error'); } }); }); $('#btnReactivateSupplier').click(function(){ $.ajax({ url: '/maintenance/supplier-active', type: 'POST', data: { supplier_name: $('#supplierName').val() }, success: function(result) { $('#add_supplier_modal').modal('toggle'); $('#SupplierReactivateModal').modal('toggle'); noty({ type: 'success', layout: 'bottomRight', timeout: 3000, text: '

Supplier successfully reactivated!

', }); table.row.add([ result.strSupplierID, result.strSupplierName, result.strSupStreet+" "+result.strSupBrgy+" "+result.strSupCity, result.strSupEmail, result.strSupplierDesc, ] ).draw(false); }, error: function(result) { alert('error'); } }); }); }); 'use strict' const fs = require('fs') const path = require('path') const rimraf = require('rimraf') exports.getCacheDir = getCacheDir function getCacheDir (index, name) { name = name || 'api' const tmpPath = path.resolve(__dirname, '../../../tmp', name) try { fs.mkdirSync(tmpPath) } catch (err) { // exists } const dir = path.resolve(tmpPath, 'test' + index) rimraf.sync(dir) return dir } paulagd/react-visualization-tool-CBIRsrc/reducers/reducer-related-images.js import * as TYPES from '../actions/types'; const INITIAL_STATE = { getRankin: {img_list:null, dataset:null, ap_system:null}, confirm:null, img_info:null ,messageError: null}; export default function(state = INITIAL_STATE, action) { switch (action.type) { case TYPES.GET_RANKIN_IMG: return Object.assign({}, state, { getRankin: { img_list: action.payload.request.data.json, ap_system:action.payload.request.data.mAP, dataset:action.payload.dataset, } }); case TYPES.GET_INFO_IMG: return Object.assign({}, state, { img_info: action.payload.encoded_image }); case TYPES.SEND_ANNOTATIONS: let accuracy = { initial: action.payload.request.data.initial, final:action.payload.request.data.final, } return Object.assign({}, state, { getRankin: { img_list: action.payload.request.data.json, accuracy, ap_system: action.payload.request.data.mAP, dataset:action.payload.dataset, confirm : action.payload.request.data.success, } }); case TYPES.RESET_ANNOTATIONS: return Object.assign({}, state, { confirm: null }); case TYPES.RESET_RANKIN_IMG: return Object.assign({}, state, { getRankin: { img_list: null, dataset: null, } }); case TYPES.ERROR_MESSAGE: // return { ...state, messageError: action.payload.data }; return Object.assign({}, state, { messageError: action.payload.data }); case TYPES.RESET_ERROR_MESSAGE: // return { ...state, messageError: action.payload.data }; return Object.assign({}, state, { messageError: null }); default: return state; } } dfcreative/color-rgba /** @module color-rgba */ 'use strict' var parse = require('color-parse') module.exports = function rgba (color) { // template literals if (Array.isArray(color) && color.raw) color = String.raw.apply(null, arguments) var values, i, l //attempt to parse non-array arguments var parsed = parse(color) if (!parsed.space) return [] var min = [0,0,0], max = parsed.space[0] === 'h' ? [360,100,100] : [255,255,255] values = Array(3) values[0] = Math.min(Math.max(parsed.values[0], min[0]), max[0]) values[1] = Math.min(Math.max(parsed.values[1], min[1]), max[1]) values[2] = Math.min(Math.max(parsed.values[2], min[2]), max[2]) if (parsed.space[0] === 'h') values = hsl2rgb(values) values.push(Math.min(Math.max(parsed.alpha, 0), 1)) return values } // excerpt from color-space/hsl function hsl2rgb(hsl) { var h = hsl[0]/360, s = hsl[1]/100, l = hsl[2]/100, t1, t2, t3, rgb, val, i=0; if (s === 0) return val = l * 255, [val, val, val]; t2 = l < 0.5 ? l * (1 + s) : l + s - l * s; t1 = 2 * l - t2; rgb = [0, 0, 0]; for (;i<3;) { t3 = h + 1 / 3 * - (i - 1); t3 < 0 ? t3++ : t3 > 1 && t3--; val = 6 * t3 < 1 ? t1 + (t2 - t1) * 6 * t3 : 2 * t3 < 1 ? t2 : 3 * t3 < 2 ? t1 + (t2 - t1) * (2 / 3 - t3) * 6 : t1; rgb[i++] = val * 255; } return rgb; } /** @author @since 17.May.2021 @desc Class that represent a cell or square of the halma board game. It has only a row and a column and its used by the model to generate an array of cells @link https://github.com/PAI-ULL/pai-practica13-halma-mvc-Adrian-alu0101024363.git Made as an excercise for the class Programación de aplicaciones interactivas de la Universidad de la Laguna */ 'use strict'; /** An ES6 Cell class that represent a piece position * @class */ export class Cell { /** @private */ /** * @property {Number} row the row of the cell/ piece * @property {Number} column the column of the cell / piece */ #row; #column; constructor(row, column) { this.#column = column; this.#row = row; } /** Get the row of the cell or piece * @returns {Number} row */ getrow() { return this.#row; } /** Get the column of the cell or piece * @returns {Number} column */ getcolumn() { return this.#column } /** Set the row of the cell or piece * @returns {Number} row */ setrow(row) { this.#row = row; } /** Set the column of the cell or piece * @returns {Number} column */ setcolumn(column) { this.#column = column; } }0 import { StyleSheet } from 'react-native' export default StyleSheet.create({ businessCardOuterWrapper: { top: 65, left: '2%', width: "96%", height: 340, }, businessCardInnerWrapper: { backgroundColor: '#fff', width: '100%', height: 250, paddingHorizontal: 15, borderRadius: 5, }, businessInfo: { flexDirection: 'row', }, businessMeta: { }, businessCardImageWrapper: { position: 'absolute', top: 0, left: '2%', width: '40%', height: 150, marginLeft: 15, borderWidth: 1, borderColor: 'transparent', borderRadius: 5, overflow: 'hidden', }, businessCardImage: { width: '100%', height: 150, borderWidth: 1, borderColor: 'transparent', borderRadius: 5, }, whitespace: { width: '45%', height: 130, }, title: { color: '#262626', }, bio: { color: '#ababab', } }) DerekKent/derekkent.com import {Controller} from 'superb'; import template from './wages.html.js'; export default class Wages extends Controller { init() { this.template = template; this.css = '/app/pages/issues/wages/wages.css'; this.view = { tag: 'main', classes: ['issues_wages-page', 'page'] }; } onLoaded() { document.title = 'Living Wages — '; } } 'use strict'; const boom = require('boom'); const makeRequest = require('../utils/make-request.js'); module.exports.get = ( { params: { apiKey, latitude, longitude, }, server, }, reply ) => makeRequest.get({ headers: { 'Accept-Encoding': 'gzip,deflate', }, host: 'api.darksky.net', path: `/forecast/${apiKey}/${latitude},${longitude}`, }) .then(reply) .catch((error) => { server.log('error', error.message); return boom.wrap(error); }); lbv/ka-cs-programs var ParserBase = $class(function() { this.tokens = []; this.cur = 0; // current token }); ParserBase.prototype.lexer = function() {}; ParserBase.prototype.end = function() { return this.cur >= this.tokens.length; }; ParserBase.prototype.peek = function() { return this.tokens[this.cur]; }; ParserBase.prototype.pop = function() { return this.tokens[this.cur++]; }; ParserBase.prototype.readToken = function(expectedType) { if (this.end()) { throw 'Reached end of input'; } var tok = this.pop(); if (tok.t !== expectedType) { throw "Invalid token " + tok.t + " (" + expectedType + " expected)"; } return tok; }; O3657/O3657-3 Building Office Apps for Outlook Using Angular and Material Design/Completed Project/Exercise03/src/appread/customers/customers-detail.controller.js1-10 (function () { 'use strict'; angular.module('officeAddin') .controller('customersDetailController', ['$q', '$window', '$location', '$routeParams', 'customerService', customersDetailController]); /** * Controller constructor * @param $q Angular's $q promise service. * @param $window Angular's $window service. * @param $location Angular's $location service. * @param $routeParams Angular's $routeParams service. * @param customerService Custom Angular service for customer data. */ function customersDetailController($q, $window, $location, $routeParams, customerService) { var vm = this; // selected customer vm.customer = {}; vm.goBack = goBack; /** *********************************************************** */ init(); /** * Initialize the controller */ function init() { // if ID is passed in, load customer var customerId = +$routeParams.customerID; if (customerId && customerId > 0) { loadCustomer(customerId); } else { $location.path('/'); } } /** * Load the specified customer. * * @param customerID {number} ID of the selected customer to display. */ function loadCustomer(customerID) { var deferred = $q.defer(); customerService.lookupCustomer(customerID) .then(function (customer) { vm.customer = customer; deferred.resolve(); }) .catch(function (error) { deferred.reject(error); }); return deferred.promise; } /** * Navigates back to the list. */ function goBack() { $window.history.back(); } } })();0 import { SIDEBAR_PROFILE } from '../actions/types'; const _initialState={ fetch: false, sidebarprofile: [] } export default function sidebarreducer(state = _initialState, action) { switch (action.type) { case SIDEBAR_PROFILE: return {...state , sidebarprofile : action.data , fetch : true , }; default: return state; } }index.js const bigIntTime = require('bigint-time') const { toBytesBE, fromBigInt, fromInt, fromBytesBE, toBigInt, MAX_UNSIGNED_VALUE } = require('longfn') function writeUint32 (target, offset, num) { target[offset] = num >>> 24 target[offset + 1] = (num >>> 16) & 0xFF target[offset + 2] = (num >>> 8) & 0xFF target[offset + 3] = num & 0xFF } function readUint32 (target, offset) { return (target[offset] * 0x1000000) + ( (target[offset + 1] << 16) | (target[offset + 2] << 8) | target[offset + 3] ) } const TMP_INT = fromInt(0) const n1e6 = BigInt(1e6) const UINT64_MAX = toBigInt(MAX_UNSIGNED_VALUE) const UINT32_MAX = 0xFFFFFFFF function bigIntCoerce (input, fallback) { if (typeof input === 'bigint') return input if (typeof input === 'number' || typeof input === 'string') return BigInt(input) return fallback } function bigIntJSON (bigInt) { if (bigInt < Number.MAX_SAFE_INTEGER) { return Number(bigInt) } return '0x' + bigInt.toString(16) } class ClockOffsetError extends Error { constructor (offset, maxOffset) { super(`The received time is ${offset / n1e6}ms ahead of the wall time, exceeding the 'maxOffset' limit of ${maxOffset / n1e6}ms.`) this.offset = offset this.maxOffset = maxOffset } } ClockOffsetError.prototype.type = 'ClockOffsetError' class WallTimeOverflowError extends Error { constructor (time, maxTime) { super(`The wall time ${time / n1e6}ms exceeds the max time of ${maxTime / n1e6}ms.`) this.time = time this.maxTime = maxTime } } WallTimeOverflowError.prototype.type = 'WallTimeOverflowError' class ForwardJumpError extends Error { constructor (timejump, tolerance) { super(`Detected a forward time jump of ${timejump / n1e6}ms, which exceed the allowed tolerance of ${tolerance / n1e6}ms.`) this.timejump = timejump this.tolerance = tolerance } } ForwardJumpError.prototype.type = 'ForwardJumpError' const codec = Object.freeze({ name: 'hlc', encode (current, byob, offset = 0) { let out if (byob) { if (byob.byteLength < 12) { throw new Error(`The provided Uint8Array is too small. 12 byte required but only ${byob.byteLength} byte given.`) } out = byob } else { out = new Uint8Array(12) } offset = byob ? offset : 0 toBytesBE(fromBigInt(current.wallTime, true, TMP_INT), offset, out) writeUint32(out, offset + 8, current.logical) return out }, decode (array, offset = 0) { return new Timestamp(toBigInt(fromBytesBE(array, true, offset, TMP_INT)), readUint32(array, offset + 8)) } }) class Timestamp { constructor (wallTime, logical = 0) { if (typeof wallTime === 'object') { this.wallTime = bigIntCoerce(wallTime.wallTime, 0n) this.logical = wallTime.logical } else { this.wallTime = bigIntCoerce(wallTime, 0n) this.logical = logical } } static compare (a, b) { if (a.wallTime > b.wallTime) return 1 if (a.wallTime < b.wallTime) return -1 if (a.logical > b.logical) return 1 if (a.logical < b.logical) return -1 return 0 } static bigger (a, b) { return a.compare(b) === -1 ? b : a } encode (byob, offset = 0) { return codec.encode(this, byob, offset) } toJSON () { return { wallTime: bigIntJSON(this.wallTime), logical: this.logical } } compare (other) { return Timestamp.compare(this, other) } } class HLC { constructor ({ wallTime, maxOffset, wallTimeUpperBound, toleratedForwardClockJump, last } = {}) { this.wallTime = wallTime || bigIntTime this.maxOffset = bigIntCoerce(maxOffset, 0n) this.wallTimeUpperBound = bigIntCoerce(wallTimeUpperBound, 0n) this.toleratedForwardClockJump = bigIntCoerce(toleratedForwardClockJump, 0n) this.last = new Timestamp(this.wallTime()) if (last) { this.last = Timestamp.bigger(new Timestamp(last), this.last) } } toJSON () { return { maxOffset: bigIntJSON(this.maxOffset), wallTimeUpperBound: bigIntJSON(this.wallTimeUpperBound), toleratedForwardClockJump: bigIntJSON(this.toleratedForwardClockJump), last: this.last.toJSON() } } now () { return this.update(this.last) } validateOffset (offset) { if (this.toleratedForwardClockJump > 0n && -offset > this.toleratedForwardClockJump) { throw new ForwardJumpError(-offset, this.toleratedForwardClockJump) } if (this.maxOffset > 0n && offset > this.maxOffset) { throw new ClockOffsetError(offset, this.maxOffset) } } update (other) { const last = Timestamp.bigger(other, this.last) let wallTime = this.wallTime() const offset = last.wallTime - wallTime this.validateOffset(offset) let logical if (offset < 0n) { logical = 0 } else { wallTime = last.wallTime logical = last.logical + 1 if (logical > UINT32_MAX) { wallTime += 1n logical = 0 } } const maxWallTime = this.wallTimeUpperBound > 0n ? this.wallTimeUpperBound : UINT64_MAX if (wallTime > maxWallTime) { throw new WallTimeOverflowError(wallTime, maxWallTime) } this.last = new Timestamp(wallTime, logical) return this.last } } HLC.Timestamp = Timestamp HLC.WallTimeOverflowError = WallTimeOverflowError HLC.ClockOffsetError = ClockOffsetError HLC.ForwardJumpError = ForwardJumpError HLC.codec = codec module.exports = HLC 0 var gulp = require('gulp'); var iconFont = require('../config/iconFont'); var images = require('../config/images'); var javascripts = require('../config/javascripts'); var sass = require('../config/sass'); var html = require('../config/html'); var watch = require('gulp-watch'); gulp.task('watch', ['browserSync'], function() { watch(images.src, function() { gulp.start('sprite');gulp.start('images'); }); watch(javascripts.src, function() { gulp.start('javascripts');gulp.start('vendor-scripts'); }); watch(sass.src, function() { gulp.start('sass'); }); watch(iconFont.src, function() { gulp.start('iconFont'); }); watch(html.src, function() { gulp.start('html'); }); }); 0 /*! * loltgt/ensemble.SocialShare * * @version 0.0.1 * @link https://github.com/loltgt/ensemble-social-share * @copyright Copyright (C) * @license MIT License */ (function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.ensemble = mod.exports; } })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports) { 'use strict'; /*! * loltgt ensemble _Symbol * * @version 0.0.1 * @link https://github.com/loltgt/ensemble * @copyright Copyright (C) * @license MIT License */ /** * @see Symbol() * * @borrows Symbol as _Symbol * @todo backward compatibility */ Object.defineProperty(_exports, "__esModule", { value: true }); _exports.SocialShare = void 0; const _Symbol = typeof Symbol == 'undefined' ? 0 : Symbol; /*! * loltgt ensemble _composition * * @version 0.0.1 * @link https://github.com/loltgt/ensemble * @copyright Copyright (C) * @license MIT License */ const REJECTED_TAG_NAMES$1 = /html|head|body|meta|link|style|script/i; const REJECTED_TAGS = /(<(html|head|body|meta|link|style|script)*>)/i; /** * Base class for ensemble.Compo and ensemble.Snap composition elements. * * @class * @abstract */ class _composition { /** * Element renderer. * * @todo TODO */ _renderer() { delete this._element; delete this._renderer; } /** * Install the composition. * * @see Node.appendChild() * * @param {Element} root - A valid Element node * @param {function} cb - A function callback * @returns {boolean} */ install(root, cb) { typeof cb == 'function' && cb.call(this, this[this._ns]); return !!root.appendChild(this[this._ns]); } /** * Uninstall the composition. * * @see Node.removeChild() * * @param {Element} root - A valid Element node * @param {function} cb - A function callback * @returns {boolean} */ uninstall(root, cb) { typeof cb == 'function' && cb.call(this, this[this._ns]); return !!root.removeChild(this[this._ns]); } /** * Loads the composition replacing a placeholder element. * * @see Node.replaceWith() * * @param {Element} pholder - A valid Element node * @param {upCallback} cb - A function callback * @returns {boolean} * @todo backward compatibility */ up(pholder, cb) { typeof cb == 'function' && cb.call(this, this[this._ns]); return !!pholder.replaceWith(this[this._ns]); } /** * Appends a compo inside this composition. * * @see Node.appendChild() * * @param {ensemble.Compo} compo - An ensemble.Compo composition * @returns {boolean} */ append(compo) { const _ns = this._ns; return !!this[_ns].appendChild(compo[_ns]); } /** * Prepends a compo inside this composition. * * @see Node.prependChild() * * @param {ensemble.Compo} compo - An ensemble.Compo composition * @returns {boolean} */ prepend(compo) { const _ns = this._ns; return !!this[_ns].prependChild(compo[_ns]); } /** * Removes a compo from this composition. * * @see Node.removeChild() * * @param {ensemble.Compo} compo - An ensemble.Compo composition * @returns {boolean} */ remove(compo) { const _ns = this._ns; return !!this[_ns].removeChild(compo[_ns]); } /** * Inject an element node inside this composition. * Note that any inner element contained will be removed. * * @see Node.appendChild() * * @constant {RegExp} REJECTED_TAG_NAMES - A regular expression for rejected tag names * @constant {RegExp} REJECTED_TAGS - A regular expression for rejected tag * @param {Element} node - A valid Element node * @returns {boolean} */ inject(node) { if (node instanceof Element == false || REJECTED_TAG_NAMES$1.test(node.tagName) || REJECTED_TAGS.test(node.innerHTML)) { throw new Error('ensemble.Compo error: The remote object could not be resolved into a valid node.'); } this.empty(); return !!this[this._ns].appendChild(node); } /** * Empty this composition. * Any inner element contained will be removed. */ empty() { while (this.first) { this.remove(this.first); } } /** * Getter for children property, intended as children compo of this composition. * * @var {getter} * @returns {array} */ get children() { return Array.prototype.map.call(this[this._ns].children, node => { return node.__compo; }); } /** * Getter for first property, intended as the first compo contained inside of this composition. * * @var {getter} * @returns {ensemble.Compo} */ get first() { const _ns = this._ns; return this[_ns].firstElementChild ? this[_ns].firstElementChild.__compo : null; } /** * Getter for last property, intended as the last compo contained inside of this composition. * * @var {getter} * @returns {ensemble.Compo} */ get last() { const _ns = this._ns; return this[_ns].lastElementChild ? this[_ns].lastElementChild.__compo : null; } } /*! * loltgt ensemble.Compo * * @version 0.0.1 * @link https://github.com/loltgt/ensemble * @copyright Copyright (C) * @license MIT License */ const REJECTED_TAG_NAMES = /html|head|body|meta|link|style|script/i; const DENIED_PROPS = /attributes|classList|innerHTML|outerHTML|nodeName|nodeType/; /** * Compo is a composition element with shorthands method and utils. * * It is a wrapper around an Element node [DOM]. * It could be used as base for abstraction of a custom component element. * * @class * @extends _composition * @inheritdoc * @example * new ensemble.Compo('namespace-of-my-foo-component', 'div', 'foo', { id: 'fooDiv', tabIndex: 1 }); */ class Compo extends _composition { /** * Constructor method. * * @constructs * @constant {RegExp} REJECTED_TAG_NAMES - A regular expression for rejected tag names * @constant {RegExp} REJECTED_TAGS - A regular expression for rejected tag * @constant {RegExp} DENIED_PROPS - A regular expression for denied properties * @param {string} ns - Component namespace * @param {string} [tag='div'] - The [DOM] Element node tag -or- component name * @param {(string|string[])} [name] - The composition name, used for CSS className * @param {object} [props] - Properties for composition * @param {object} [options] - An optional ElementCreationOptions object [DOM] * @param {object} [elementNS] - Options for namespaced Element node [DOM] * @param {string} [elementNS.namespaceURI] - A valid namespace URI * @param {string} [elementNS.qualifiedName] - A valid qualified name * @todo props.dataset */ constructor(ns, tag, name, props, options, elementNS) { if (!new.target) { throw 'ensemble.Compo error: Bad invocation, must be called with new.'; } super(); const _ns = this._ns = '_' + ns; const ctag = tag ? tag.toString() : 'div'; if (REJECTED_TAG_NAMES.test(tag)) { throw new Error(`ensemble.Compo error: The tag name provided ('${ctag}') is not a valid name.`); } const node = this[_ns] = this._element(ns, ctag, name, props, options, elementNS); this.__Compo = true; this[_ns].__compo = this; if (props && typeof props == 'object') { for (const prop in props) { const cprop = prop.toString(); if (DENIED_PROPS.test(cprop)) { throw new Error(`ensemble.Compo error: The property name provided ('${cprop}') is not a valid name.`); } if (cprop.indexOf('on') === 0 && props[cprop] && typeof props[cprop] == 'function') { node[cprop] = props[cprop].bind(this); //TODO // } else if (cprop == 'dataset' && typeof props[cprop] == 'object') { // node.dataset = Object.assign(node.dataset, props[cprop]); } else if (typeof props[cprop] != 'object') { node[cprop] = props[cprop]; } else if (cprop == 'children') { if (typeof props[cprop] == 'object' && props[cprop].length) { for (const child of props.children) { const tag = child.tag; const name = child.name; const props = child.props; this.append(new Compo(ns, tag, name, props)); } } } } } if (name) { const _name = node.className; node.className = ''; if (typeof name == 'string') { node.className = ns + '-' + name; } else if (typeof name == 'object') { node.className = name.map(a => ns + '-' + a).join(' '); } if (_name) { node.className += ' ' + _name; } } this._renderer(); } /** * Element wrapper. * * @see document.createElement() * @see document.createElementNS() * * @param {string} ns - Component namespace * @param {string} tag - The element Node tag -or- component name * @param {string} name - Name for composition, used for CSS className * @param {object} props - Properties for composition * @param {object} [options] - An optional ElementCreationOptions object [DOM] * @param {object} [elementNS] - Options for namespaced Element node [DOM] * @param {string} [elementNS.namespaceURI] - A valid namespace URI * @param {string} [elementNS.qualifiedName] - A valid qualified name */ _element(ns, tag, name, props, options, elementNS) { if (elementNS) return document.createElementNS(tag, [...elementNS, ...options]);else return document.createElement(tag, options); } /** * Check for an attribute of this composition. * * @see Element.hasAttribute() * * @param {string} attr - An attribute * @returns {boolean} */ hasAttr(attr) { return this[this._ns].hasAttribute(attr); } /** * Gets an attribute from this composition. * * @see Element.getAttribute() * * @param {string} attr - An attribute * @returns {string} */ getAttr(attr) { return this[this._ns].getAttribute(attr); } /** * Sets an attribute in this composition. * * @see Element.setAttribute() * * @param {string} attr - An attribute * @param {string} value - The value */ setAttr(attr, value) { this[this._ns].setAttribute(attr, value); } /** * Removes an attribute from this composition. * * @see Element.removeAttribute() * * @param {string} attr - An attribute */ delAttr(attr) { this[this._ns].removeAttribute(attr); } /** * Gets a current style property. * * @see window.getComputedStyle() * * @param {string} prop - A style property * @returns {mixed} */ getStyle(prop) { return window.getComputedStyle(this[this._ns])[prop]; } /** * Time to show this composition. */ show() { this[this._ns].hidden = false; } /** * Time to hide this composition. */ hide() { this[this._ns].hidden = true; } /** * Util to set attribute disabled to true */ enable() { this[this._ns].disabled = false; } /** * Util to set attribute disabled to false */ disable() { this[this._ns].disabled = true; } /** * Getter for node property, intended as the Element node inside this composition. * Note that a direct access to the node is discouraged. * * @var {getter} * @returns {Element} */ get node() { console.warn('ensemble.Compo', 'Direct access to the node is strongly discouraged.'); return this[this._ns]; } /** * Getter for parent property, intended as the parent compo of this composition. * * @var {getter} * @returns {ensemble.Compo} */ get parent() { const _ns = this._ns; return this[_ns].parentElement && '__compo' in this[_ns].parentElement ? this[_ns].parentElement.__compo : null; } /** * Getter for previous property, intended as the previous sibling of this composition. * * @var {getter} * @returns {ensemble.Compo} */ get previous() { const _ns = this._ns; return this[_ns].previousElementSibling ? this[_ns].previousElementSibling.__compo : null; } /** * Getter for next property, intended as the next sibling of this composition. * * @var {getter} * @returns {ensemble.Compo} */ get next() { const _ns = this._ns; return this[_ns].nextElementSibling ? this[_ns].nextElementSibling.__compo : null; } /** * Getter for classList property, intended as the classList of the Element node inside this composition. * * @see DOMTokenList * * @var {getter} * @returns {DOMTokenList} */ get classList() { return this[this._ns].classList; } /** * Check if passed object is an ensemble.Compo instance. * * @static * @returns {boolean} * @todo backward compatibility */ static isCompo(obj) { if (_Symbol) return _Symbol.for(obj) === _Symbol.for(Compo.prototype);else return obj && typeof obj == 'object' && '__Compo' in obj; } /** * Getter for Symbol property, returns the symbolic name for ensemble.Compo class. * * @see Symbol.toStringTag() * * @override * @returns {string} * @todo return undef * @todo backward compatibility */ get [_Symbol.toStringTag]() { return 'ensemble.Compo'; } } /*! * loltgt ensemble.Data * * @version 0.0.1 * @link https://github.com/loltgt/ensemble * @copyright Copyright (C) * @license MIT License */ /** * Data is a multi-purpose utility object. * * It could be used as a wrapper around a Compo composition, * this object can store any kind of properties. * * @class * @example * new ensemble.Data('namespace-of-my-foo-component', { compo: ensemble.Compo, foo: 'a text string', fooObj: 'an object' }); */ class Data { /** * Constructor method. * * @constructs * @param {string} ns - Data namespace * @param {object} obj - A starter Object */ constructor(ns, obj) { if (!new.target) { throw 'ensemble.Data error: Bad invocation, must be called with new.'; } if (obj && typeof obj == 'object') { Object.assign(this, {}, obj); } const _ns = this._ns = '_' + ns; this.__Data = true; this[_ns] = { ns }; } /** * The compo method is a utility render. * * When you create a composition with this method, it will create a Compo composition or simply an Object placeholder. * With the defer render you can have it rendered in place, refresh, or freeze. * * @param {string} tag - Element node tag -or- component name * @param {string} name * @param {object} props - Properties for Element node -or- component * @param {boolean} defer - Defer render for composition * @param {mixed} fresh - A function callback, called when is loaded the compo * @param {mixed} stale - A function callback, called when is unloaded the compo * @returns {mixed} compo - An ensemble.Compo element -or- an Object placeholder */ compo(tag, name, props, defer = false, fresh = false, stale = false) { const ns = this[this._ns].ns; let compo; if (defer) { compo = { ns, tag, name, props, fresh, stale }; } else { compo = new Compo(ns, tag, name, props); } if (fresh && typeof fresh == 'function') { compo.fresh = props.onfresh = fresh; } if (stale && typeof stale == 'function') { compo.stale = props.onstale = stale; } return compo; } /** * Renderizes a composition, passed by reference. * * @async * @param {mixed} slot - Reference of the element that will be rendered */ async render(slot) { const _ns = this._ns; if (this[_ns][slot] && this[_ns][slot].rendered) { this[_ns][slot].fresh(); } else { this[_ns][slot] = { rendered: true, fresh: this[slot].fresh, stale: this[slot].stale, params: this[slot] }; this[slot] = new Compo(this[slot].ns, this[slot].tag, this[slot].name, this[slot].props); this[_ns][slot].fresh(); } } /** * Freezes a composition, passed by reference. * * @async * @param {mixed} slot - Reference of the element that will be rendered */ async stale(slot) { const _ns = this._ns; if (this[_ns][slot] && this[_ns][slot].rendered) { this[_ns][slot].stale(); } } /** * Refresh a composition, passed by reference. * * @async * @param {mixed} slot - Reference of the element that will be rendered. * @param {boolean} force - It forces the reflow. */ async reflow(slot, force) { const _ns = this._ns; if (force) { this[_ns][slot] = this.compo(this[_ns][slot].params.ns, this[_ns][slot].params.name, this[_ns][slot].params.props); } else if (this[_ns][slot] && this[_ns][slot].rendered) { this[_ns][slot].fresh(); } } /** * Check if passed object is an ensemble.Data instance. * * @static * @returns {boolean} * @todo backward compatibility */ static isData(obj) { if (_Symbol) return _Symbol.for(obj) === _Symbol.for(Data.prototype);else return obj && typeof obj == 'object' && '__Data' in obj; } /** * Getter for Symbol property, returns the symbolic name for ensemble.Data class. * * @see Symbol.toStringTag * * @override * @returns {string} * @todo return undef * @todo backward compatibility */ get [_Symbol.toStringTag]() { return 'ensemble.Data'; } } /*! * loltgt ensemble.Event * * @version 0.0.1 * @link https://github.com/loltgt/ensemble * @copyright Copyright (C) * @license MIT License */ /** * Event is an event manager. * * It is a wrapper around the native Event [DOM]. * * @class * @example * new ensemble.Event('namespace-of-my-foo-component', 'mousewheel', node).add(func, { capture: true }); */ class Event { /** * Constructor method. * * @see Element.addEventListener() * @see Element.removeElementListener() * * @constructs * @param {string} ns - Event namespace * @param {string} name - The [DOM] Event type name * @param {Element} node - A valid Element node -or- component */ constructor(ns, name, node) { if (!new.target) { throw 'ensemble.Event error: Bad invocation, must be called with new.'; } const _ns = this._ns = '_' + ns; node = (Compo.isCompo(node) ? node.node : node) || document; this.__Event = true; this[_ns] = { name, node }; } /** * Adds an event for this composition. * * @see Element.addEventListener() * * @param {function} handle - The function handler * @param {mixed} options - An options Object -or- useCapture boolean */ add(handle, options = false) { this[this._ns].node.addEventListener(this[this._ns].name, handle, options); } /** * Removes an event from this composition. * * @see Element.removeElementListener() * * @param {function} handle - The function handler * @todo ? removes handle ref. */ remove(handle) { this[this._ns].node.removeEventListener(this[this._ns].name, handle); } /** * Check if passed object is an ensemble.Event instance. * * @static * @returns {boolean} * @todo backward compatibility */ static isEvent(obj) { if (_Symbol) return _Symbol.for(obj) === _Symbol.for(Event.prototype);else return obj && typeof obj == 'object' && '__Event' in obj; } /** * Getter for Symbol property, returns the symbolic name for ensemble.Event class. * * @see Symbol.toStringTag * * @override * @returns {string} * @todo return undef * @todo backward compatibility */ get [_Symbol.toStringTag]() { return 'ensemble.Event'; } } /*! * loltgt ensemble.base * * @version 0.0.1 * @link https://github.com/loltgt/ensemble-stack-d1 * @copyright Copyright (C) * @license MIT License */ /** * A base class for ensemble components. * * @class * @abstract * @param {Element} [element] - A valid element, could be used within the extending class * @param {object} options - Options object * @example * new base([, element], options) */ class base { /** * Constructor method. */ constructor() { const tname = 'ensemble' + (new.target && new.target.name ? '.' + new.target.name : ''); let element, options; if (arguments.length > 1) { element = arguments[0]; options = arguments[1]; } else { options = arguments[0]; } if (options && typeof options != 'object') { throw new TypeError(`${tname} error: The passed argument 'options' is not of type Object.`); } if (element && typeof element != 'object') { throw new TypeError(`${tname} error: The passed argument 'element' is not of type Object.`); } this._bindings(); this.options = this.defaults(this._defaults(), options); Object.freeze(this.options); this.element = element; } /** * Creates an options Object from a defaults object of pre-defined properties. * * Note it supports only the first level of depth. * * @param {object} defaults - The default options Object * @param {object} options - An options Object that would extends * @returns {object} */ defaults(defaults, options) { const j = {}; for (const k in defaults) { if (defaults[k] != null && typeof defaults[k] == 'object') { j[k] = Object.assign(defaults[k], options[k]); } else { j[k] = typeof options[k] != 'undefined' ? options[k] : defaults[k]; } } return j; } /** * Shorthand method for ensemble.Compo class. * * When passed the first argument it makes a new Compo instance, * otherwise it returns a reference to the Compo class. * * @param {string} ns - Composition namespace * @param {string} [tag='div'] - The [DOM] Element node tag -or- component name, empty for ensemble.Compo class reference * @param {mixed} [name] - The composition name, used for CSS className * @returns {mixed} Instance of ensemble.Data -or- ensemble.Data class reference */ compo(tag, name, props) { return tag != undefined ? new Compo(this.options.ns, tag, name, props) : Compo; } /** * Shorthand method for ensemble.Data class. * * When passed the first argument it makes a new Data instance, * otherwise it returns a reference to the Data class. * * @param {object} obj - A starter Object, empty for ensemble.Data class reference * @returns {mixed} Instance of ensemble.Data -or- ensemble.Data class reference */ data(obj) { return obj != undefined ? new Data(this.options.ns, obj) : Data; } /** * Shorthand method for ensemble.Event class. * * When the passed first argument is a string it makes a new Event instance, * if you pass an Event as the first argument, a preventDefault and blur will be performed, * otherwise it returns a reference to the Event class. * * @param {object} obj - A starter Object, empty for ensemble.Event class reference * @returns {mixed} */ event(event, node) { if (typeof event == 'string') { return new Event(this.options.ns, event, node); } else if (event) { event.preventDefault(); event.target.blur(); } else { return Event; } } /** * Shortcut to querySelectorAll() and querySelector() [DOM]. * * @see Element.querySelectorAll() * @see Element.querySelector() * * @param {string} query - A text query * @param {Element} node - An Element node where find * @param {boolean} all - Find single or multiple elements * @return {mixed} - Element -or- ElementCollection */ selector(query, node, all = false) { node = node || document; return all ? node.querySelectorAll(query) : node.querySelector(query); } /** * Shortcut to appendChild() [DOM]. * * @see Element.appendChild() * * @param {Element} parent - An Element parent * @param {Element} node - An Element node to append * @returns {boolean} */ appendNode(parent, node) { return !!parent.appendChild(node); } /** * Shortcut to prependChild() [DOM]. * * @see Element.prependChild() * * @param {Element} parent - An Element parent * @param {Element} node - An Element node to prepend * @returns {boolean} */ prependNode(parent, node) { return !!parent.prependChild(node); } /** * Shortcut to cloneNode() [DOM]. * * @see Element.removeNode() * * @param {Element} parent - An Element parent * @param {Element} node - An Element node to remove * @returns {boolean} */ removeNode(root, node) { return !!root.removeChild(node); } /** * Shortcut to Element.cloneNode() [DOM]. * * @see Element.cloneNode() * * @param {Element} node - An Element node to clone * @param {boolean} deep - Clone also all children inside the Element node * @returns {boolean} */ cloneNode(node, deep = false) { return node.cloneNode(deep); } /** * Shortcut to Element.hasAttribute() [DOM]. * * @see Element.hasAttribute() * * @param {Element} node - An Element node * @param {string} attr - An attribute * @returns {boolean} */ hasAttr(node, attr) { return node.hasAttribute(attr); } /** * Shortcut to Element.getAttribute() [DOM]. * * @see Element.getAttribute() * * @param {Element} node - An Element node * @param {string} attr - An attribute * @returns {string} */ getAttr(node, attr) { return node.getAttribute(attr); } /** * Shortcut to Element.setAttribute() [DOM]. * * @see Element.setAttribute() * * @param {Element} node - An Element node * @param {string} attr - An attribute * @param {string} value - The value */ setAttr(node, attr, value) { node.setAttribute(attr, value); } /** * Shortcut to Element.removettribute() [DOM]. * * @see Element.removeAttribute() * * @param {Element} node - An Element node * @param {string} attr - An attribute */ delAttr(node, attr) { node.removeAttribute(attr); } /** * Creates a proxy function with bindings to instance and optionally an event. * * @param {function} method - A method from the current instance * @returns {function} * @todo untrusted method */ binds(method) { const self = this; return function (e) { method.call(self, e, this); }; } /** * Provides a delay and executes a callback function * * @see window.setTimeout() * * @param {function} func - A function callback * @param {mixed} node - An Element node -or- an ensemble.Compo composition * @param {int} dtime - A default value of time in milliseconds */ delay(func, node, dtime) { const delay = node ? this.timing(node) : 0; setTimeout(func, delay || dtime); } /** * Calculates a time, based on a time property of the style of an element * * @see window.getComputedStyle() * * @param {mixed} node - An Element node -or- an ensemble.Compo composition * @param {string} prop - A style property * @returns {int} time - Number of time in milliseconds */ timing(node, prop = 'transitionDuration') { let time = Compo.isCompo(node) ? node.getStyle(prop) : window.getComputedStyle(node)[prop]; if (time) { time = time.indexOf('s') ? parseFloat(time) * 1e3 : parseInt(time); } return time || 0; } } /*! * loltgt ensemble.SocialShare * * @version 0.0.1 * @link https://github.com/loltgt/ensemble-social-share * @copyright Copyright (C) * @license MIT License */ /** * ensemble.SocialShare component. * * @class * @extends base * @inheritdoc * @param {Element} [element] - A valid Element node that will be replaced with this component * @param {object} options - Options object * @param {string} [options.ns=share] - The namespace for social share * @param {string} [options.root=body] - The root Element node * @param {(string|string[])} [options.className=social-share] - The component CSS class name * @param {string} [options.link=''] - The link, leave empty to auto-discover with selector or location.href * @param {string} [options.title=''] - The title, leave empty to auto-discover with selector or window.title * @param {string} [options.description=''] - The description, leave empty to auto-discover with selector * @param {object} [options.displays=null] - What actions to display, default to all * @param {object} [options.intents] - Action intents * @param {object} [options.uriform] - URI strings * @param {object} [options.label] - Custom parameters for label * @param {object} [options.selectorLink] - An element selector to find link * @param {object} [options.selectorTitle] - An element selector to find title * @param {object} [options.selectorDescription] - An element selector to find description * @param {object} [options.locale] - Localization * @param {function} [options.onInit] - onInit callback, fires when social share is initialized * @param {function} [options.onIntent] - onIntent callback, fires when an action is called * @example * var share = new ensemble.SocialShare(document.getElementById('my-div-placeholder'), {}); * @todo arguments */ class SocialShare extends base { /** * Options object default properties. * * @returns {object} */ _defaults() { return { ns: 'share', fx: true, root: 'body', className: 'social-share', link: '', title: '', description: '', displays: null, intents: { 'facebook': 0, 'twitter': 0, 'whatsapp': 1, 'messenger': 1, 'telegram': 1, 'linkedin': 0, 'send-email': 2, 'copy-link': 3, 'web-share': 4 }, uriform: { 'facebook': 'https://facebook.com/sharer.php?u=%url%', 'twitter': 'https://twitter.com/share?url=%url%&text=%title%', 'whatsapp': 'https://api.whatsapp.com/send?text=%text%', 'messenger': 'fb-messenger://share/?link=%url%&app_id=%app_id%', 'telegram': 'https://telegram.me/share/url?url=%url%&text=%text%', 'linkedin': 'https://www.linkedin.com/sharing/share-offsite?mini=true&url=%url%&title=%title%&ro=false&summary=%summary%', 'send-email': 'mailto:?subject=%subject%&body=%text%' }, selectorLink: { element: 'link[rel="canonical"]', attribute: 'href' }, selectorTitle: null, selectorDescription: { element: 'meta[name="description"]', attribute: 'content' }, label: {}, locale: { label: 'Share', share: 'Share on %s', send: 'Send to %s', subject: 'An interesting thing', text: 'Hi! There is something may interesting you: %s', email: 'Send via email', copy: 'Copy link', copied: 'Copied link!', 'whatsapp': 'WhatsApp', 'linkedin': 'LinkedIn', 'web-share': 'Share' }, onInit: function () {}, onIntent: function () {} }; } /** * Methods binding. */ _bindings() { this.intent = this.binds(this.intent); } /** * Constructor method. */ constructor() { if (!new.target) { throw 'ensemble.SocialShare error: Bad invocation, must be called with new.'; } super(...arguments); this.init(); } /** * The generator creates almost everything the component needs and replaces the element placeholder. * * @todo dataset */ generator() { const opts = this.options; const share = this.share = this.compo(false, false, { className: typeof opts.className == 'object' ? opts.className.join(' ') : opts.className }); //TODO // dataset share.setAttr('data-social-share', ''); if (opts.label) { const label = this.compo('span', 'label', opts.label); label.classList.add('label'); if ('innerText' in opts.label == false) { label.innerText = opts.locale.label; } share.append(label); } const actions = this.actions = this.compo('ul', 'actions'); share.append(actions); this.built = true; } /** * Initializes the component. * * @todo TODO */ init() { const opts = this.options; if (this.built) return; this.root = this.selector(opts.root); this.displays = opts.displays && typeof opts.displays == 'object' ? opts.displays : Object.keys(opts.intents); this.generator(); if (this.element) { this.share.up(this.element, function (node) { this.element = node; }.bind(this)); } this.populate(); opts.onInit.call(this, this); } /** * In this stage the component is populated with all the content progeny. * * @see window.navigator.share() */ populate() { const opts = this.options; for (const intent in opts.intents) { if (this.displays.indexOf(intent) == -1) continue; const name = intent in opts.locale ? opts.locale[intent] : intent.replace(/\w/, cap => cap.toUpperCase()); let title; switch (opts.intents[intent]) { case 0: title = opts.locale.share.replace('%s', name); break; case 1: title = opts.locale.send.replace('%s', name); break; case 2: title = opts.locale.email; break; case 3: title = opts.locale.copy; break; case 4: if (!('share' in window.navigator && typeof window.navigator.share == 'function')) { continue; } title = opts.locale['web-share']; break; } this.action(intent, title); } } /** * Creates the whole set of buttons. * * @param {string} intent - The activity name * @param {string} title - A title for activity * @todo dataset */ action(intent, title) { const opts = this.options; const action = this.compo('li', 'action', { className: opts.ns + '-action-' + intent }); const button = this.compo('button', ['button', 'intent'], { className: opts.ns + '-intent-' + intent, title, ariaLabel: title, onclick: this.intent }); //TODO // dataset action.setAttr('data-share-intent', intent); action.append(button); const icon = this.compo('span', 'icon', { className: 'icon-' + intent }); button.append(icon); this.actions.append(action); } /** * The intent activity. * This method is called from each action. * * @see window.location * * @param {Event} e - An Event * @param {Element} target - The element that is invoking * @todo url validation */ intent(e, target) { this.event(e); if (!e.isTrusted) return; const opts = this.options; if (!this.compo().isCompo(target)) return; const action = target.parent; if (!(action && action.hasAttr('data-share-intent'))) return; const intent = action.getAttr('data-share-intent'); if (this.displays.indexOf(intent) == -1) return; let url, title, summary, text; if (opts.link) { url = opts.link; } else if (opts.selectorLink && typeof opts.selectorLink == 'object' && this.selector(opts.selectorLink.element)) { url = this.getAttr(this.selector(opts.selectorLink.element), opts.selectorLink.attribute); } else { url = window.location.href; } if (opts.title) { title = opts.title; } else if (opts.selectorTitle && typeof opts.selectorTitle == 'object' && this.selector(opts.selectorTitle.element)) { title = this.getAttr(this.selector(opts.selectorTitle.element), opts.selectorTitle.attribute); } else { title = document.title; } if (opts.description) { summary = opts.description; } else if (opts.selectorDescription && typeof opts.selectorDescription == 'object' && this.selector(opts.selectorDescription.element)) { summary = this.getAttr(this.selector(opts.selectorDescription.element), opts.selectorDescription.attribute); } else { summary = title; } text = '\r\n\r\n%title%\r\n%url%\r\n\r\n'; const data = { url, title, text, summary }; opts.onIntent.call(this, this, e, intent, data); data.text = opts.locale.text.replace('%s', data.text); if (intent in opts.intents) { switch (intent) { case 'send-email': this.sendEmail(e, data); break; case 'copy-link': this.copyLink(e, data); break; case 'web-share': this.webShare(e, data); break; default: this.social(e, data, intent, action); } } } /** * Makes text substitutions and encodes to an URL * * @param {object} data - The data object * @param {string} data.url - Shared URL * @param {string} data.title - Shared title * @param {string} data.text - Shared description text * @param {string} data.summary - Shared summary * @return {string} - The encoded URL text string */ text(data) { return encodeURIComponent(data.text.replace('%url%', data.url).replace('%title%', data.title).replace('%summary%', data.summary)); } /** * Generic social method for social network sharing intent. * * @see window.open() * * @param {Event} e - An Event * @param {object} data - The data object * @param {string} data.url - Shared URL * @param {string} data.title - Shared title * @param {string} data.text - Shared description text * @param {string} data.summary - Shared summary */ social(e, data, intent, action) { const opts = this.options; if (intent in opts.uriform == false) return; let url = opts.uriform[intent].replace('%url%', encodeURIComponent(data.url)).replace('%title%', encodeURIComponent(data.title)).replace('%summary%', encodeURIComponent(data.summary)); //TODO const title = action.getAttr('ariaLabel'); const options = 'toolbar=0,status=0,width=640,height=480'; if (/%text%/.test(opts.uriform[intent])) { url = url.replace('%text%', this.text(data)); } if (intent == 'messenger') { const app_id = 'messenger_app_id' in opts ? opts.messenger_app_id : ''; url = url.replace('%app_id%', encodeURIComponent(app_id)); } console.log(url, title, options); window.open(url, title, options); } /** * Send email intent, it tries to open the default mail client. * * @see window.open() * * @param {Event} e - An Event * @param {object} data - The data object * @param {string} data.url - Shared URL * @param {string} data.title - Shared title * @param {string} data.text - Shared description text * @param {string} data.summary - Shared summary */ sendEmail(e, data) { const opts = this.options; const url = opts.uriform['send-email'].replace('%subject%', encodeURIComponent(opts.locale.subject)).replace('%text%', this.text(data)); console.log(url, '_self'); window.open(url, '_self'); } /** * Copy link intent, it tries to copy URL on the clipboard. * * @see document.createElement() * @see document.execCommand() * * @param {Event} e - An Event * @param {object} data - The data object * @param {string} data.url - Shared URL * @param {string} data.title - Shared title * @param {string} data.text - Shared description text * @param {string} data.summary - Shared summary * @todo TODO */ copyLink(e, data) { if (!this.element) return; const opts = this.options; const cb = document.createElement('textarea'); cb.style = 'position:absolute;width:0;height:0;opacity:0;z-index:-1;overflow:hidden'; cb.value = data.url.toString(); this.appendNode(this.element, cb); //TODO obsolete (safari mobile | crios?) // if (/iPad|iPhone|iPod/.test(window.navigator.userAgent)) { // const sr = document.createRange(); // const gs = getSelection(); // sr.selectNodeContents(cb); // gs.removeAllRanges(); // gs.addRange(sr); // cb.setSelectionRange(0, 999999); // } else { cb.focus(); cb.select(); // } document.execCommand('copy'); cb.remove(); if (opts.fx) { const root = this.root; const gnd = this.compo(false, 'fx-copied-link--ground', { hidden: true }); const msg = this.compo('span', 'copied-link-message', { innerText: opts.locale.copied }); root.classList.add('share-fx-copied-link'); gnd.install(root); msg.install(root); gnd.show(); this.delay(function () { msg.uninstall(root); gnd.uninstall(root); root.classList.remove('share-fx-copied-link'); }, gnd, 8e2); } } /** * Calls the native WebShare API for sharing. * * @see window.navigator.share() * * @async */ async webShare(e, data) { try { await window.navigator.share({ title: data.title, url: data.url }); } catch (err) { if (err instanceof TypeError) { console.info('ensemble.SocialShare.webShare', 'TODO fallback'); } else { console.log('ensemble.SocialShare.webShare', err.message); } } } } _exports.SocialShare = SocialShare; });({"previousMessage":"Previous choices","nextMessage":"More choices"})const createRenderer = (canvas) => { const { width, height } = canvas const context = canvas.getContext('2d') context.imageSmoothingEnabled = false var imageData = context.getImageData(0, 0, width, height) var buf = new ArrayBuffer(imageData.data.length) var buf8 = new Uint8ClampedArray(buf) var data = new Uint32Array(buf) const render = (world, colors) => { for (let i = 0; i < world.length; i++) data[i] = colors[world[i]] imageData.data.set(buf8); context.putImageData(imageData, 0, 0) } return { render } } export default createRenderer/*--- { "skip": true } ---*/ /*=== done fulfill: 123 ===*/ var P = Promise.try(function () { return 123; }); P.then(function (v) { print('fulfill:', v); }, function (e) { print('reject:', e); }); print('done'); (function(){ document.addEventListener('DOMContentLoaded',function(){ }); })(); import React, { useState } from "react"; import { Paper, TableContainer, TableBody, Table, TableCell, TableRow, TablePagination, Button, } from "@material-ui/core"; import { setLearnerIdToDisable, setLearnerIdToEnable } from "../LearnerSlice"; import useStyles from "./LearnerTable.styles"; import EnhancedToolbar from "../../../hoc/EnhancedTableToolbar/EnhancedTableToolbar"; import EnhancedTableHead from "../../../components/EnhancedTableHead/EnhancedTableHead"; import { withStyles } from "@material-ui/core/styles"; import SimpleBar from "simplebar-react"; import { useDispatch } from "react-redux"; const StyledTableRow = withStyles(() => ({ root: { "&:nth-of-type(odd)": { backgroundColor: `rgba(26, 115, 232, 0.1)`, }, }, }))(TableRow); const LearnerTable = (props) => { const classes = useStyles(); const dispatch = useDispatch(); const [rowsPerPage, setRowsPerPage] = useState(10); const [page, setPage] = useState(0); const [order, setOrder] = useState("asc"); const [orderBy, setOrderBy] = useState("name"); const headCells = [ { id: "#", label: "#", }, { id: "fullName", label: "", }, { id: "email", isNumber: true, label: "email", }, { id: "createdAt", label: "Created At", }, { id: "actions", label: "Actions", }, ]; const handleChangePage = (e, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (e) => { setRowsPerPage(parseInt(e.target.value, 10)); setPage(0); }; const descendingComparator = (a, b, orderBy) => { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; }; const getComparator = (order, orderBy) => { return order === "desc" ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); }; const stableSort = (array, comparator) => { const stabilizedThis = array.map((el, index) => [el, index]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); return stabilizedThis.map((el) => el[0]); }; const createSortHandler = (property) => () => { const isAsc = orderBy === property && order === "asc"; setOrder(isAsc ? "desc" : "asc"); setOrderBy(property); }; const emptyRows = rowsPerPage - Math.min(rowsPerPage, props.learners.length - page * rowsPerPage); return (
{stableSort(props.learners, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row, index) => ( {rowsPerPage * page + index + 1} {row.fullName} {row.userCredential.email} {row.createdAt} {row.userCredential.isActive ? ( ) : ( )} ))} {/* {emptyRows > 0 && ( )} */}
); }; export default LearnerTable; frontend/build/precache-manifest.056fe1f056abbf09f8a2c5522d6ed01d.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { revision: "7290f320688195cb1a8d03a039df234e", url: "/index.html", }, { revision: "78a3c5e255b0b38ceb7d", url: "/static/css/main.d42a640a.chunk.css", }, { revision: "8866fb49b0d288a3af19", url: "/static/js/2.bacb37bb.chunk.js", }, { revision: "78a3c5e255b0b38ceb7d", url: "/static/js/main.b9b9e738.chunk.js", }, { revision: "b5bb8bb98a91bf60f4bd", url: "/static/js/runtime-main.8a2e4473.js", }, { revision: "5d5d9eefa31e5e13a6610d9fa7a283bb", url: "/static/media/logo.5d5d9eef.svg", }, ]); evaletolab/geospatial-resources var status = function(code, message){ return function(maybe_message){ return { code: code, message: maybe_message || message }; }; }; module.exports = { ok: status(0, 'operation succesful'), uninitialized_gps_position: status(1, 'uninitialized gps position'), story_ended: status(2, 'story ended (no more narrative positions)') }; 1-10 'use strict' module.exports = { description: 'Runs state machines defined in Amazon States Language', blueprintDirs: { 'state-machines': 'Each JSON file inside this sub-directory will be used to conjure a State Machine for orchestrating a workflow. Tymly uses the open [Amazon State Language](https://states-language.net/spec.html) to describe State Machines.' } } monosidev/monosidocumentation/src/components/index.js export {default as ResponsivePlayer} from "./responsive-player/ResponsivePlayer"; export {Button} from "./shared/Button"; export {Integrations} from "./Integrations"; export {MonosiCloud} from "./MonosiCloud"; export {Community} from "./Community"; export {Intro} from "./Intro"; export {Resources} from "./Resources"; export {Newsletter} from "./Newsletter"; import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { Link, Redirect } from 'react-router-dom'; import { tokenSignInRequest } from '../../actions/userAuth-actions.js'; import { userProfileFetchRequest, userProfileUpdateRequest } from '../../actions/userProfile-actions.js'; import { currentLocationFetchRequest } from '../../actions/map-actions.js'; import { userValidation, logError, renderIf } from './../../lib/util.js'; class MyWallet extends React.Component { constructor(props){ super(props); this.state = { }; } componentWillMount() { userValidation(this.props); } render() { return (

My wallet

Congrats you've got

10.63

Previous Payments

We June 4

La Belle vie

5

Th June 6

Le comptoire des saveurs

3

Mo June 12

4

); } } let mapStateToProps = state => ({ userAuth: state.userAuth, userProfile: state.userProfile, currentLocation: state.currentLocation, }); let mapDispatchToProps = dispatch => ({ tokenSignIn: token => dispatch(tokenSignInRequest(token)), userProfileFetch: () => dispatch(userProfileFetchRequest()), userProfileUpdate: profile => dispatch(userProfileUpdateRequest(profile)), currentLocationFetch: () => dispatch(currentLocationFetchRequest()), }); export default connect(mapStateToProps, mapDispatchToProps)(MyWallet);packages/ui/src/redux/selectors/ratesSelector.js import { createSelector } from 'reselect'; import { parseNumberToLocale } from '../../helpers/numberFormatter'; import BigNumber from 'bignumber.js'; import { selectedInstrumentDecimalPlacesSelector, selectedInstrumentSelector, } from './instrumentPositionSelectors'; import { buyValue } from '../../constants/sendOrder/orderEntryFormConstants'; import { getOrderFormInfoBrandSpecificSelector } from './buySellSelectors'; import { selectAccountFeeByType } from './userSelectors'; import { getBalanceWithProductSymbol } from 'helpers/productHelper'; import { formatNumberToLocale } from 'helpers/numberFormatter'; import { getOrderFee, getOrderPricePerUnit, isMakerOrTaker, } from 'helpers/orderHelper'; import { getPriceForGetOrderFeeRequest } from 'helpers/recalculateOrderHelper'; import { makerFeeValue, takerFeeValue, takerValue, } from 'constants/sendOrder/makerTakerConstants'; const isBuySideBuySellFormSelector = createSelector( [(state) => state.form.buySell], (formObj) => { return formObj ? formObj.values.side === buyValue : true; } ); export const getGoldRatesSelector = createSelector( [(state) => state], (state) => { const goldInstrument = state.instrument.instruments.find( (inst) => inst.Symbol === 'GOLDUSD' ); const goldInstrumentId = goldInstrument && goldInstrument.InstrumentId ? goldInstrument.InstrumentId : 41; const inst = state.level1[goldInstrumentId]; return { Bid: (inst && inst.BestBid) || 0, Ask: (inst && inst.BestOffer) || 0, isFetching: !inst, }; } ); export const getOrderInfoFormattedSelector = createSelector( [ (state) => state, getOrderFormInfoBrandSpecificSelector, selectedInstrumentSelector, selectedInstrumentDecimalPlacesSelector, isBuySideBuySellFormSelector, ], (state, selectedValue, selectedInstrument, decimalPlaces, isBuySide) => { const quantity = selectedValue.quantity ? selectedValue.quantity : 0; const price = selectedValue.price ? selectedValue.price : 0; const limitPrice = selectedValue.limitPrice ? selectedValue.limitPrice : 0; const pricePerUnit = selectedValue.pricePerUnit ? selectedValue.pricePerUnit : 0; const { Product1Symbol, Product2Symbol } = selectedInstrument; const { form: { buySell: buySellForm = { values: { fee: {} } } }, position, } = state; const { OrderFee = 0 } = buySellForm.values.fee; const selectedLevel1Data = state.level1[selectedInstrument.InstrumentId]; const checkIsMakerOrTakerFee = isMakerOrTaker( buySellForm.values.side, getPriceForGetOrderFeeRequest( buySellForm.values.price, selectedLevel1Data ), selectedLevel1Data?.BestBid, selectedLevel1Data?.BestOffer, buySellForm.values.orderType ) === takerValue ? takerFeeValue : makerFeeValue; const feePercentage = selectAccountFeeByType(state, checkIsMakerOrTakerFee); const actualPrice = new BigNumber(price).minus(OrderFee); const actualQuantity = parseNumberToLocale(buySellForm.values.quantity) > 0 ? new BigNumber(buySellForm.values.quantity).minus(OrderFee) : 0; return { quantity: formatNumberToLocale(quantity, decimalPlaces[Product1Symbol]), actualQuantity: formatNumberToLocale( actualQuantity, decimalPlaces[Product1Symbol] ), limitPrice, pricePerUnit: getBalanceWithProductSymbol( Product2Symbol, getOrderPricePerUnit( pricePerUnit, Product1Symbol, Product2Symbol, decimalPlaces, isBuySide ), true ), feePercentage: feePercentage, feeFormatted: getOrderFee(buySellForm, position.positions, 'end'), actualPrice: getBalanceWithProductSymbol( Product2Symbol, formatNumberToLocale( actualPrice, decimalPlaces[Product2Symbol], isBuySide ? BigNumber.ROUND_CEIL : BigNumber.ROUND_FLOOR ), true ), totalPrice: getBalanceWithProductSymbol( Product2Symbol, formatNumberToLocale( price, decimalPlaces[Product2Symbol], isBuySide ? BigNumber.ROUND_CEIL : BigNumber.ROUND_FLOOR ), true ), price: getBalanceWithProductSymbol( Product2Symbol, formatNumberToLocale( price, decimalPlaces[Product2Symbol], isBuySide ? BigNumber.ROUND_CEIL : BigNumber.ROUND_FLOOR ), true ), }; } ); const path = require('path'); module.exports = { merchantId: '92061101', merchantName: 'Test shop', merchantCertificateId: '00C182B189', certPrvPass: '', certPrv: path.resolve(__dirname, './cert.prv'), certPub: path.resolve(__dirname, './cert.pub'), kkbcaPub: path.resolve(__dirname, './kkbca_test.pub'), serverEndpoint: 'https://testpay.kkb.kz', }; 0 //カレンダー用クラス var compCalendar = Class.create(); var calendarComp = Array(); /* モジュール側のjavascriptクラスから this.calendar = new compCalendar(id, text_el, options); @param string top_id @param text_el or string text_el_id text_elの後ろにカレンダーアイコンを挿入する @param object options onClickCallback 日付選択時コールバック関数 parentFrame text_elがあるFrame(default:document) designatedDate 日付指定(20070101のように指定) 日付指定されていれば、テキストエリアの日付に有無にかかわらず優先される calendarImgPath カレンダーImgPath(themes/images/icons) calendarColorDir カレンダーColorDir(default) calendarImg テキスト横につくカレンダーアイコンimage(style/images/icons/下) calendarThemeDir カレンダーCSSの定義ファイルDir(htdocs/css/comp/XXX/comp_calendar.css) default: default */ compCalendar.prototype = { initialize: function(id, text_el, options) { this.id = id; this.popup = null; this.text_el = null; this.calendarIcon_el = null; this.options = { onClickCallback: null, parentFrame: "", onClickCallback: null, designatedDate: "", pre_show_week: 0, // 前月0週目まで表示(0-3) next_show_week: 1, // 次月1週目まで表示(0-3) calendarImgPath: _nc_core_base_url + "/themes/images/icons", calendarColorDir: "default", calendarImg: "calendar.gif", calendarThemeDir: "default" }; Object.extend(this.options, options || {}); // private this.date = null; this.todayYear = null; this.todayMonth = null; this.todayDay = null; this.selectedYear = null; this.selectedMonth = null; this.selectedDay = null; this.currentYear = null; this.currentMonth = null; this.currentDay = null; this.currentDate = null; this.setDesignatedDateFlag = false; this.Mdays = {"01":"31", "02":"28", "03":"31", "04":"30", "05":"31", "06":"30", "07":"31", "08":"31", "09":"30", "10":"31", "11":"30", "12":"31"}; // 1ブロック内に複数、カレンダーコンポーネントを張ってあった場合の対応 var key = id; var count = 1; while (calendarComp[key]) { key = id + "_" + count; count++; } calendarComp[key] = this; this.key = key; ////calendarComp[id + this.calendar_classname] = this; this._showCalendarImg(text_el); }, //------------------------------ // 表示指定日セット //------------------------------ setDesignatedDate: function(yyyymmdd) { this.options.designatedDate = yyyymmdd; }, //------------------------------ // 日付移動クリック //------------------------------ onMoveClick: function(yyyymmdd) { this.currentYear = yyyymmdd.substr(0, 4); this.currentMonth = yyyymmdd.substr(4, 2); this.currentDay = yyyymmdd.substr(6, 2); this.currentDate = yyyymmdd; var popup_el = this.popup.getPopupElement(); popup_el.contentWindow.document.body.innerHTML = this._render(); this.popup.resize(); }, //------------------------------ // 日付クリック //------------------------------ onDayClick: function(yyyymmdd) { var day_separator = (compCalendarLang.day_separator != undefined) ? compCalendarLang.day_separator : "/"; //callbackが指定されていれば実行、そうでなければ、this.text_elがinput type="text"ならば代入 if(this.options.onClickCallback != null) { this.options.onClickCallback(yyyymmdd); } else { if(this.text_el.tagName.toLowerCase() == 'input' && this.text_el.type.toLowerCase() == 'text') { this.text_el.value = yyyymmdd.substr(0, 4)+ day_separator + yyyymmdd.substr(4, 2) + day_separator + yyyymmdd.substr(6, 2); commonCls.focus(this.text_el); } } this._popupClose(); }, //---------------------------------------------------------- // カレンダー使用有効・無効処理 value=true or false //---------------------------------------------------------- disabledCalendar: function(value) { this.text_el.disabled = value; if(value) { this.text_el.blur(); this.calendarIcon_el.blur(); Element.addClassName(this.calendarIcon_el, "display-none"); if (this.popup != null) { this.popup.closePopup(this.popup.getPopupElement()); } } else { Element.removeClassName(this.calendarIcon_el, "display-none"); commonCls.focus(this.text_el); } }, //------------------------------ // カレンダーボタン表示処理 //------------------------------ _showCalendarImg: function(text_el) { if(typeof text_el == 'string') { if(this.options.parentFrame == "" || this.options.parentFrame == null) { text_el = $(text_el); } else { text_el = this.options.parentFrame.contentWindow.document.getElementById(text_el); } } if(typeof text_el != 'object') return; if(this.options.parentFrame == "" || this.options.parentFrame == null) { var calendarA_el = document.createElement("a"); var calendarImg_el = document.createElement("img"); } else { var calendarA_el = this.options.parentFrame.contentWindow.document.createElement("a"); var calendarImg_el = this.options.parentFrame.contentWindow.document.createElement("img"); } calendarA_el.href = "#"; calendarImg_el.src = this.options.calendarImgPath + "/" + this.options.calendarColorDir + "/" + this.options.calendarImg; Element.addClassName(calendarA_el, "comp_calendar_icon"); if(text_el.tagName.toLowerCase() == 'input' && text_el.type.toLowerCase() == 'text') { Element.addClassName(text_el, "comp_calendar_text"); } calendarImg_el.alt = (compCalendarLang.icon_alt != undefined) ? compCalendarLang.icon_alt : "Calendar"; calendarImg_el.title = (compCalendarLang.icon_title != undefined) ? compCalendarLang.icon_title : "Show Calendar"; text_el.parentNode.insertBefore(calendarA_el, text_el); text_el.parentNode.insertBefore(text_el, calendarA_el); calendarA_el.appendChild(calendarImg_el); Event.observe(calendarA_el, "click", function(event){ this._showCalendar(); Event.stop(event); }.bindAsEventListener(this), false, this.id); this.text_el = text_el; this.calendarIcon_el = calendarA_el; }, //------------------------------ // カレンダー表示処理 //------------------------------ _showCalendar: function() { // 今日の日付 this.date = new Date(); this.todayYear = this._getFormat(this.date.getFullYear()); //文字列変換 this.todayMonth = this._getFormat(this.date.getMonth() + 1); this.todayDay = this._getFormat(this.date.getDate()); if(this.setDesignatedDateFlag == true) { // 初期化 this.options.designatedDate = null; this.setDesignatedDateFlag = false; } if((this.options.designatedDate == null || this.options.designatedDate == "") && this.text_el.tagName.toLowerCase() == 'input' && this.text_el.type.toLowerCase() == 'text') { var sel_date = this.text_el.value; if(sel_date.length == 10) { var sel_year = sel_date.substr(0, 4); var sel_month = sel_date.substr(5, 2); var sel_day = sel_date.substr(8, 2); if(valueParseInt(sel_month) > 0 && valueParseInt(sel_month) < 13 && valueParseInt(sel_day) > 0 && valueParseInt(sel_day) < 32) { //yyyy/mm/ddの形式チェックのみ行っている this.setDesignatedDateFlag = true; this.options.designatedDate = sel_year + sel_month + sel_day; } } } // 指定した日付 if(this.options.designatedDate == null || this.options.designatedDate == "") { this.selectedYear = null; this.selectedMonth = null; this.selectedDay = null; this.currentYear = this.todayYear; this.currentMonth = this.todayMonth; this.currentDay = "01"; } else { this.selectedYear = this.options.designatedDate.substr(0, 4); this.selectedMonth = this.options.designatedDate.substr(4, 2); this.selectedDay = this.options.designatedDate.substr(6, 2); this.currentYear = this.selectedYear; this.currentMonth = this.selectedMonth; this.currentDay = "01"; } this.currentDate = this.currentYear + this.currentMonth + this.currentDay; var html = this._render(); if(!this.popup) { this.popup = new compPopup(this.id, "compCalendar"); var new_dir_name ="/comp/"+this.options.calendarThemeDir+"/comp_calendar.css"; var css_name = _nc_core_base_url + _nc_index_file_name + "?action=common_download_css&dir_name="+new_dir_name+"&header=0"; this.popup.addCSSFiles(css_name); this.popup.observer = function(event) {this._popupClose(); }.bind(this); //this.popup.loadObserver = function(event) { // this.popup.resize(); //}.bind(this); } if(this.options.parentFrame) { this.popup.setLapPosition(this.calendarIcon_el, this.options.parentFrame); this.popup.showPopup(html); } else { this.popup.showPopup(html, this.calendarIcon_el); } }, _getNextYear: function(yyyy, mm, dd) { yyyy = valueParseInt(yyyy) + 1; // 文字列として連結 return this._getFormat(yyyy) + this._getFormat(mm) + this._getFormat(dd); }, _getPrevYear: function(yyyy, mm, dd) { yyyy = valueParseInt(yyyy) - 1; if(yyyy < 1900) { yyyy = 1900; } // 文字列として連結 return this._getFormat(yyyy) + this._getFormat(mm) + this._getFormat(dd); }, _getNextDate: function(yyyy, mm, dd) { mm = valueParseInt(mm) + 1; if(mm == 13) { mm = 1; yyyy = valueParseInt(yyyy) + 1; } // 文字列として連結 return this._getFormat(yyyy) + this._getFormat(mm) + this._getFormat(dd); }, _getPrevDate: function(yyyy, mm, dd) { mm = valueParseInt(mm) - 1; if(mm <= 0) { mm = 12; yyyy = valueParseInt(yyyy) - 1; } // 文字列として連結 return this._getFormat(yyyy) + this._getFormat(mm) + this._getFormat(dd); }, _getFormat: function(num) { return (valueParseInt(num) < 10) ? ("0" + valueParseInt(num)) : "" + num; }, //yy,mm の月の日数を返す _getMonthDays: function(yy, mm) { if(mm == "02") { if ((yy % 4) == 0) { return "29"; } else if ((yy % 100) == 0) { return "28"; } else if ((yy % 400) == 0) { return "29"; //閏年の処理終了 } } return this.Mdays[mm]; }, //曜日のインデックス(0-6)を返す。 _getWeekDays: function(yyyy,mm,dd) { var now = new Date(valueParseInt(yyyy), valueParseInt(mm) - 1, valueParseInt(dd)); var w = now.getDay(); return w; }, _render: function() { var next_year = this._getNextYear(this.currentYear, this.currentMonth, this.currentDay); var prev_year = this._getPrevYear(this.currentYear, this.currentMonth, this.currentDay); var next_month = this._getNextDate(this.currentYear, this.currentMonth, this.currentDay); var prev_month = this._getPrevDate(this.currentYear, this.currentMonth, this.currentDay); var pre_end_date = this._getMonthDays(prev_month.substr(2, 2), prev_month.substr(4, 2)); var end_date = this._getMonthDays(this.currentYear.substr(2, 2), this.currentMonth); var start_w = this._getWeekDays(this.currentYear, this.currentMonth, this.currentDay); if(start_w == 0) { if(this.options.pre_show_week != 0) { var pre_start_date = pre_end_date - 7*this.options.pre_show_week + 1; } else { var pre_start_date = 0; } } else { var pre_start_date = pre_end_date - 7*this.options.pre_show_week - (start_w - 1); } var loop_week = valueParseInt(Math.ceil((valueParseInt(end_date) + start_w + 7*this.options.pre_show_week + 7*this.options.next_show_week) / 7)); var currentMonth = valueParseInt(this.currentMonth); //if(currentMonth < 10) currentMonth = " " + currentMonth; switch (currentMonth) { case 1: currentMonth = compCalendarLang.month_jan; break; case 2: currentMonth = compCalendarLang.month_feb; break; case 3: currentMonth = compCalendarLang.month_mar; break; case 4: currentMonth = compCalendarLang.month_apr; break; case 5: currentMonth = compCalendarLang.month_may; break; case 6: currentMonth = compCalendarLang.month_jun; break; case 7: currentMonth = compCalendarLang.month_jul; break; case 8: currentMonth = compCalendarLang.month_aug; break; case 9: currentMonth = compCalendarLang.month_sep; break; case 10: currentMonth = compCalendarLang.month_oct; break; case 11: currentMonth = compCalendarLang.month_nov; break; case 12: currentMonth = compCalendarLang.month_dec; break; default: } var html = "
" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; var pre_outside_day = pre_start_date; var current_day = 1; var post_end_date = 1; for (var i = 0; i < loop_week; i++) { html += ""; for (var j = 0; j < 7; j++) { if(pre_outside_day > 0) { var day_class = "compcalendar_outside"; var day = pre_outside_day; if(pre_end_date < day+1) { pre_outside_day = 0 } else { pre_outside_day++; } var prefix_day_click = prev_month.substr(0, 6); } else if(current_day > 0) { var day = current_day; if (end_date < day+1) { current_day = 0; } else { current_day++; } if (j == 0) { var day_class="compcalendar_sun"; } else if(j == 6) { var day_class="compcalendar_sat"; } else { var day_class="compcalendar_weekday"; } //<{* 選択中の日付 *}> if (this.currentYear == this.selectedYear && this.currentMonth == this.selectedMonth && this.selectedDay == day) { day_class += " compcalendar_highlight"; } //<{* 今日の日付 *}> if (this.currentYear == this.todayYear && this.currentMonth == this.todayMonth && this.todayDay == day) { day_class += " compcalendar_today"; } var prefix_day_click = this.currentYear + this.currentMonth; } else { var day_class = "compcalendar_outside"; var day = post_end_date; post_end_date++ var prefix_day_click = next_month.substr(0, 6); } //<{* Td *}> html += ""; } html += ""; } html += "
" + this.currentYear + compCalendarLang.year + " " + currentMonth + "
" + "" + //<{* « *}> compCalendarLang.btn_prev_year + "" + "" + "" + //<{* ‹ *}> compCalendarLang.btn_prev_month + "" + "" + "" + //<{* 今日へ *}> compCalendarLang.move_today + "" + "" + "" + //<{* › *}> compCalendarLang.btn_next_month + "" + "" + "" + //<{* » *}> compCalendarLang.btn_next_year + "" + "
" + //<{* 日 *}> compCalendarLang.week_sun + "" + //<{* 月 *}> compCalendarLang.week_mon + "" + //<{* 火 *}> compCalendarLang.week_tue + "" + //<{* 水 *}> compCalendarLang.week_wed + "" + //<{* 木 *}> compCalendarLang.week_thu + "" + //<{* 金 *}> compCalendarLang.week_fri + "" + //<{* 土 *}> compCalendarLang.week_sat + "
" + "" + day + "" + "
" + "
"; return html; }, _popupClose: function() { this.popup.closePopup(this.popup.getPopupElement()); if(this.text_el.tagName.toLowerCase() == 'input' && this.text_el.type.toLowerCase() == 'text') { commonCls.focus(this.text_el); } } }i1oy/Practice_JavaScript "use strict" function main() { { // The Undefined Type var val; console.log("The Type of val: " + (typeof val)); console.log("The Type of val2: " + (typeof val2)); console.log(); } { // The Null Type // 如果定义的变量准备将来用于保存对象, // 那么最好将该变量初始化为null var obj = null; console.log("The type of obj: " +(typeof obj)); // 'object' console.log(); } { // The Boolean Type // ECMAScript中所有类型的值均有与true和false等价的值, // 可以调用Boolean函数进行转换 var found = true; var lost = false; var message = "Hello world."; var messageAsBoolean = Boolean(message); if (messageAsBoolean === found) { console.log(message); console.log(); } } { // The Number Type // 使用IEEE754-2008格式来表示整数与浮点数值 //Integer var intNum = 18; // var octalNum = 022; //Octal literals are not allowed in strict mode. var hexNum = 0x12; console.log("intNum = " + intNum + "\n"); // console.log("octalNum = " + octalNum + "\n"); console.log("hexNum = " + hexNum + "\n"); //Float // 浮点数值的计算会产生舍入误差, // 故不要测试某个特定的浮点值 var pi = 3.14; // 数值转换 var num = Number("18"); var num2 = parseInt("123BLUE"); // 123 var num3 = parseInt("0x12"); // 18 var num4 = parseInt("12", 16); // 18 var floatNum = parseFloat("3.14159"); } { // The String Type // 转义序列将被作为一个字符来解析 var text = "This is the letter sigma: \u03A3"; console.log(text); // 转为字符串 var age = 18; var ageAsString = age.toString(); // '18' var found = true; var foundAsStirng = found.toString(); // "true" } { // The Object Type // ECMAScript中的对象其实就是一组数据和功能的集合 } } main();import React from "react" const Home = ({version}) => { const [isUpdate, setIsUpdate] = React.useState(false) const update = React.useCallback(() => { setIsUpdate(true) fetch("http://localhost:5000/updateP2N") .then(function(response) { setIsUpdate(false) }) }, []) return (

Patent2Net Docker Version : {version}


Patent2Net is a toolkit for patent information processing and statistical analysis for education and science.
Patent2Net helps to collect, study and analyze patent data from the European Patent Office’s Open Patent Services API (OPS).
Patent2Net is a free software dedicated to :

  • provide statistical analysis and representations of a set of patents.
  • promote the use of patent information in the academic field, nano and small firms, developing countries.
  • study and practice how to collect, treat and communicate “textual bibliographic information” and learn the automation process.

Contributions are always welcome!


To update your P2N version click on the button :

) } export default Home0 /** * @ngdoc module * @name subrosa.game * * @description * Module for game related functionality. */ angular.module('subrosa.game', [ 'geolocation', 'i18n', 'ngResource', 'subrosa.components.flash', 'subrosa.components.form', 'subrosa.components.map', 'subrosa.components.modal', 'subrosa.player', 'subrosa.utils', 'ui.router', 'ui.bootstrap.datepicker', 'ui.bootstrap.timepicker' ]); /** * @ngdoc object * @name subrosa.game.config * * @requires $stateProvider * * @description * Set up the game state machine. */ angular.module('subrosa.game').config(function ($stateProvider) { 'use strict'; $stateProvider.state('games', { url: '/games', controller: 'GameListController', templateUrl: '/app/game/views/game-list.html' }); $stateProvider.state('create-game', { url: '/new-game', controller: 'CreateGameController', templateUrl: '/app/game/create/views/create-game.html' }); $stateProvider.state('game', { url: '/game/{gameUrl}', controller: 'GameController', views: { '@': { controller: 'GameController', templateUrl: '/app/game/views/game.html' }, 'header@game': { templateUrl: '/app/game/views/game-header.html' }, 'content@game': { controller: 'GameFeedController', templateUrl: '/app/game/views/game-feed.html' }, 'menu@game': { templateUrl: '/app/game/views/game-menu.html' } } }); $stateProvider.state('game.info', { url: '/info', views: { 'content@game': { templateUrl: '/app/game/views/game-info.html' } } }); $stateProvider.state('game.map', { url: '/map', views: { 'content@game': { templateUrl: '/app/game/views/game-map.html' } } }); $stateProvider.state('game.statistics', { url: '/statistics', views: { 'content@game': { templateUrl: '/app/game/views/game-stats.html' } } }); $stateProvider.state('game.join', { url: '/join', views: { 'content@game': { controller: 'JoinGameController', templateUrl: '/app/game/join/views/join-game.html' } } }); $stateProvider.state('game.join.register', { url: '/register', controller: 'RegisterFormController', templateUrl: '/app/account/views/register-form.html' }); $stateProvider.state('game.join.select-player', { url: '/select-player', controller: 'JoinGameSelectPlayerController', templateUrl: '/app/game/join/views/join-game-select-player.html' }); $stateProvider.state('game.join.player-info', { url: '/player-info', controller: 'JoinGamePlayerInfoController', templateUrl: '/app/game/join/views/join-game-player-info.html' }); $stateProvider.state('game.edit', { url: '/edit', views: { 'header@game': { controller: 'EditGameController', templateUrl: '/app/game/edit/views/edit-game-header.html' }, 'content@game': { templateUrl: '/app/game/edit/views/edit-game.html' }, 'menu@game': { templateUrl: '/app/game/edit/views/edit-game-menu.html' } } }); $stateProvider.state('game.edit.rules', { url: '/rules', views: { 'content@game': { controller: 'EditGameRulesController', templateUrl: '/app/game/edit/views/edit-game-rules.html' } } }); $stateProvider.state('game.edit.enrollment', { url: '/join-game-form', views: { 'content@game': { controller: 'EditJoinGameFormController', templateUrl: '/app/game/edit/views/edit-join-game-form.html' } } }); $stateProvider.state('game.edit.zone', { url: '/zone', views: { 'content@game': { controller: 'EditGameZoneController', templateUrl: '/app/game/edit/views/edit-game-zone.html' } } }); $stateProvider.state('game.edit.events', { url: '/events', views: { 'content@game': { controller: 'EditGameEventsController', templateUrl: '/app/game/edit/views/edit-game-events.html' }, '': { templateUrl: '/app/game/edit/views/edit-game-events-scheduled.html' } } }); $stateProvider.state('game.edit.events.triggered', { url: '/events/triggered', views: { '': { templateUrl: '/app/game/edit/views/edit-game-events-triggered.html' } } }); }); api/src/services/blogPosts/blogPosts.test.js import { blogPosts } from './blogPosts'; describe('blogPosts', () => { scenario('returns all blogPosts', async (scenario) => { const result = await blogPosts(); expect(result.length).toEqual(Object.keys(scenario.blogPost).length); }); }); module.exports = { base: '/bekit/', title: 'Bekit', locales: { '/': { lang: 'en-US', description: 'Smart Front-End Kit' }, '/zh/': { lang: 'zh-CN', description: '小巧的前端业务工具集' } }, themeConfig: { locales: { '/': { selectText: 'Languages', label: 'English', ariaLabel: 'Languages', // editLinkText: 'Edit this page on GitHub', // serviceWorker: { // updatePopup: { // message: "New content is available.", // buttonText: "Refresh" // } // }, algolia: {}, nav: [ { text: 'Home', link: '/' }, { text: 'Guides', link: '/guide/' }, { text: 'GitHub', link: 'https://github.com/luzimingx/bekit' }, ], sidebar: [{ title: 'Guides', path: null, collapsable: false, sidebarDepth: 2, children: [ ['/guide/', 'Quick Start'], ['/guide/url/', 'Url'], ['/guide/ls/', 'Local Storage'], ['/guide/ua/', 'UserAgent'], ['/guide/dom/', 'DOM'], ['/guide/time/', 'Date'], ['/guide/factory/', 'Factory'], ['/guide/notice/', 'Notice'], ['/guide/plugin/', 'Plugin'] ] }], lastUpdated: 'Last Updated' }, '/zh/': { selectText: '选择语言', label: '简体中文', // editLinkText: '在 GitHub 上编辑此页', // serviceWorker: { // updatePopup: { // message: "发现新内容可用.", // buttonText: "刷新" // } // }, // 当前 locale 的 algolia docsearch 选项 algolia: {}, nav: [ { text: '首页', link: '/zh/' }, { text: '指南', link: '/zh/guide/' }, { text: 'GitHub', link: 'https://github.com/luzimingx/bekit' }, ], sidebar: [{ title: '指南', path: null, collapsable: false, sidebarDepth: 2, children: [ ['/zh/guide/', '快速上手'], ['/zh/guide/url/', '链接'], ['/zh/guide/ls/', 'Local Storage'], ['/zh/guide/ua/', 'userAgent'], ['/zh/guide/dom/', 'DOM'], ['/zh/guide/time/', '日期'], ['/zh/guide/factory/', '工厂函数'], ['/zh/guide/notice/', '通知'], ['/zh/guide/plugin/', '插件'] ] }], lastUpdated: 'Last Updated' } } } };/** * @test * @title PunyJS.ui.gui.template._DOMFragmentManager: kitchen sink */ function domFragmentManagerTest1( controller , mock_callback ) { var domFragmentManager, dom_createElement, dom_createElementNS, dom_mutationObserver, domProxy, fragmentId, eventFn, element, observer, dom_createTextNode, changeHandler, mutationHandler, template_element, fragment, eventOffFn; arrange( async function arrangeFn() { eventFn = mock_callback( function mockOnEvent(event, handler) { changeHandler = handler } ); eventOffFn = mock_callback(); domProxy = { "tagName": "repeat" , "attributes": { "expr": "$f in list" } , "on": eventFn , "off": eventOffFn , "children": [ { "tagName": "div" , "on": eventFn , "children": [ { "tagName": "text" , "attributes": { "text": "test value" } } ] } , { "tagName": "toolbar" , "attributes": { "id": "toolbarId" , "name": "toolbar" } , "on": eventFn , "children": [ { "tagName": "text" , "attributes": { "text": "->" } } , { "tagName": "toolbar-icon" , "attributes": { "alt-text": "alternate" , "url": "url://" } , "on": eventFn } ] } ] }; element = { "setAttribute": mock_callback() , "appendChild": mock_callback() , "parentElement": { "removeChild": mock_callback() } }; template_element = mock_callback("template element"); observer = { "observe": mock_callback() , "disconnect": mock_callback() }; dom_createElement = mock_callback(element); dom_createElementNS = mock_callback(element); dom_createTextNode = mock_callback(element); dom_mutationObserver = mock_callback( function mockCallback(handler) { mutationHandler = handler; return observer; } ); domFragmentManager = await controller( [ ":PunyJS.ui.gui.template._DOMFragmentManager" , [ dom_createElement , dom_createElementNS , dom_createTextNode , dom_mutationObserver , template_element ] ] ); } ); act( function actFn() { fragmentId = domFragmentManager.create( domProxy ); fragment = domFragmentManager.get( fragmentId ); domFragmentManager.destroy( fragmentId ); } ); assert( function assertFn(test) { test("The createElement callback should be called once for the root") .value(dom_createElementNS) .hasBeenCalled(1) .hasBeenCalledWithArg(0, 0, "http://www.w3.org/1999/xhtml") .hasBeenCalledWithArg(0, 1, "repeat") ; test("The createElement callback should be called 5x with") .value(dom_createElement) .hasBeenCalled(3) .hasBeenCalledWithArg(0, 0, "div") .hasBeenCalledWithArg(1, 0, "toolbar") .hasBeenCalledWithArg(2, 0, "toolbar-icon") ; test("The element.setAttribute callback should be called 5x with") .value(element, "setAttribute") .hasBeenCalled(5) .hasBeenCalledWithArg(0, 0, "expr") .hasBeenCalledWithArg(0, 1, "$f in list") .hasBeenCalledWithArg(1, 0, "id") .hasBeenCalledWithArg(1, 1, "toolbarId") ; test("The element.appendChild callback should be called 5x with") .value(element, "appendChild") .hasBeenCalled(5) .hasBeenCalledWithArg(0, 0, element) .hasBeenCalledWithArg(1, 0, element) .hasBeenCalledWithArg(2, 0, element) .hasBeenCalledWithArg(3, 0, element) .hasBeenCalledWithArg(4, 0, element) ; test("The dom_mutationObserver should be called once") .value(dom_mutationObserver) .hasBeenCalled(1) ; test("The mutation observe callback should be called once") .value(observer, "observe") .hasBeenCalled(1) .hasBeenCalledWithArg(0, 0, element) .getCallbackArg(0, 1) .stringify() .equals('{"childList":true,"attributes":true,"subtree":true}') ; test("The on event should only be called twice") .value(eventFn) .hasBeenCalled(2) .hasBeenCalledWithArg(0, 0, "*") .hasBeenCalledWithArg(1, 0, "delete *") ; test("The template_element should be called once with") .value(template_element) .hasBeenCalled(1) .hasBeenCalledWithArg(0, 0, element) ; test("The fragment from the get operation should be") .value(fragment) .equals("template element") ; test("The observer disconnect should be called once") .value(observer, "disconnect") .hasBeenCalled(1) ; test("The parent removeChild should be called once") .value(element, "parentElement.removeChild") .hasBeenCalled(1) .hasBeenCalledWithArg(0, 0, element) ; test("The off event callback should be called once") .value(eventOffFn) .hasBeenCalled(1) .hasBeenCalledWithArg(0, 0, "*") .hasBeenCalledWithArg(0, 1, changeHandler) ; } ); } /** * @test * @title PunyJS.ui.gui.template._DOMFragmentManager: mutation */ function domFragmentManagerTest2( controller , mock_callback ) { var domFragmentManager, domProxy, fragmentId, eventFn, element, observer, dom_createTextNode, changeHandler, mutationHandler, template_element, fragment, eventOffFn; arrange( async function arrangeFn() { eventFn = mock_callback( function mockOnEvent(event, handler) { changeHandler = handler } ); eventOffFn = mock_callback(); domProxy = { "tagName": "repeat" , "attributes": { "expr": "$f in list" } , "on": eventFn , "off": eventOffFn , "children": [ { "tagName": "div" , "on": eventFn , "children": [ { "tagName": "text" , "attributes": { "text": "test value" } } ] } , { "tagName": "toolbar" , "attributes": { "id": "toolbarId" , "name": "toolbar" } , "on": eventFn , "children": [ { "tagName": "text" , "attributes": { "text": "->" } } , { "tagName": "toolbar-icon" , "attributes": { "alt-text": "alternate" , "url": "url://" } , "on": eventFn } ] } ] }; template_element = mock_callback( function mockTemplateElement(element) { return element } ); domFragmentManager = await controller( [ ":PunyJS.ui.gui.template._DOMFragmentManager" , [ , , , , template_element ] ] ); } ); act( function actFn() { fragmentId = domFragmentManager.create( domProxy ); element = domFragmentManager.get( fragmentId ); element.childNodes[1].childNodes[1] .setAttribute( "newattrib" , "new value" ); element.appendChild( element.childNodes[1].childNodes[0] ); } ); assert( function assertFn(test) { test("The proxy should have a new attribute") .value(domProxy, "children.1.children.0.attributes.newattrib") .equals("new value") ; test("The element outerHTML should be") .value(element, "outerHTML") .equals('
test value
->
') ; } ); } /** * @test * @title PunyJS.ui.gui.template._DOMFragmentManager: kitchen sink */ function domFragmentManagerTest3( controller , mock_callback ) { var domFragmentManager, domProxy, fragmentId, eventFn, changeHandler, fragment, eventOffFn, element; arrange( async function arrangeFn() { eventFn = mock_callback( function mockOnEvent(event, handler) { changeHandler = handler } ); eventOffFn = mock_callback(); domProxy = { "tagName": "repeat" , "attributes": { "expr": "$f in list" } , "on": eventFn , "off": eventOffFn , "children": [ { "tagName": "div" , "on": eventFn , "children": [ { "tagName": "text" , "attributes": { "text": "test value" } } ] } , { "tagName": "toolbar" , "attributes": { "id": "toolbarId" , "name": "toolbar" } , "on": eventFn , "children": [ { "tagName": "text" , "attributes": { "text": "->" } } , { "tagName": "toolbar-icon" , "attributes": { "alt-text": "alternate" , "url": "url://" } , "on": eventFn } ] } ] }; domFragmentManager = await controller( [ ":PunyJS.ui.gui.template._DOMFragmentManager" , [ ] ] ); } ); act( function actFn() { fragmentId = domFragmentManager.create( domProxy ); changeHandler( { "action": "set" , "key": "children[0].attributes.newattrib" , "value": "new attrib value" , "miss": true } ); changeHandler( { "action": "delete" , "key": "children[1].children[1].attributes.alt-text" , "miss": false } ); changeHandler( { "action": "set" , "key": "children[0].children[2]" , "value": { "tagName": "div-append" , "attributes": { "attrib1": "value1" } } , "arrayAction": "append" , "miss": true } ); changeHandler( { "action": "set" , "key": "children[0].children[0]" , "value": { "tagName": "div-insert" , "attributes": { "attrib1": "value1" } } , "arrayAction": "insert" , "miss": true } ); element = domFragmentManager.get( fragmentId ); } ); assert( function assertFn(test) { test("The element should be") .value(element, "outerHTML") .equals('
test value
->
') ; } ); }jahammo2/veery module.exports = [ require('./barracudas'), require('./beyuCaffe'), require('./bottle501'), require('./egos'), require('./fondaKaraokeSantaGuadalupe'), require('./skewersBarAndGrill'), require('./theWaterTank') ]; 'use strict'; const fs = require('fs'); const path = require('path'); const LanguageParser = require('./parser/LanguageParser'); const TokenAnalyzer = require('./parser/TokenAnalyzer'); const nodeGen = require('./generator/NodeGen'); const CodeGenerator = require('./CodeGenerator'); const languagePath = path.join(__dirname, '../steam_language'); const cwd = process.cwd(); process.chdir(languagePath); const tokenList = LanguageParser.tokenizeString(fs.readFileSync('steammsg.steamd', {encoding: 'ascii'})); const root = TokenAnalyzer.analyze(tokenList); process.chdir(cwd); const rootEnumNode = new TokenAnalyzer.Node(); const rootMessageNode = new TokenAnalyzer.Node(); rootEnumNode.childNodes = root.childNodes.filter(n => n instanceof TokenAnalyzer.EnumNode); rootMessageNode.childNodes = root.childNodes.filter(n => n instanceof TokenAnalyzer.ClassNode); CodeGenerator.emitCode(rootEnumNode, nodeGen); CodeGenerator.emitCode(rootMessageNode, nodeGen); notes-server/notes/notes.controller.js0 require('express-hateoas-links'); const express = require('express'); const router = express.Router(); const notesService = require('./notes.service'); // routes router.post('/', createNote); router.get('/:noteId', getNote); router.get('/', getNotes); router.put('/:noteId', updateNote); router.delete('/:noteId', deleteNote); router.post('/attachment', uploadFile) module.exports = router; function createNote(req, res, next) { notesService.createNote(req.body) .then(note => res.status(200).json(note, defaultLinks(note.id))) .catch(err => next(err)) } function getNote(req, res, next) { notesService.getNote(req.params.noteId) .then(note => note ? res.status(200).json(note, defaultLinks(note.id)) : res.sendStatus(404)) .catch(err => next(err)); } function getNotes(req, res, next) { const url = 'http://127.0.0.1/notes/'; notesService.getNotes() .then(notes => { res.status(200).json(notes, [ {rel: "self", method: "GET", href: url}, {rel: "create", method: "POST", title: 'Create Note', href: url} ]) }).catch(err => next(err)); } function updateNote(req, res, next) { notesService.updateNote({noteId : req.params.noteId, noteData: req.body}) .then(note => res.status(200).json(note, defaultLinks(note.id))) .catch(err => next(err)); } function deleteNote(req, res, next) { notesService.deleteNote(req.params.noteId) .then(note => res.status(200).json(note)) .catch(err => next(err)); } function uploadFile(req, res, next) { notesService.uploadFile(req, res) .then(note => res.status(200).json(note)) .catch(err => next(err)) } /* Generates hateoas links to be included to response body */ let defaultLinks = (noteId) => { const url = 'http://127.0.0.1/notes/'; return [ {rel: "self", method: "GET", href: url + noteId || ''}, {rel: "create", method: "POST", title: 'Create Note', href: url}, {rel: "update", method: "PUT", title: 'Update Note', href: url + noteId || ''}, {rel: "delete", method: "DELETE", title: 'Delete Note', href: url + noteId || ''} ] };JuanPablo2655/cobalt-bot const mongoose = require('mongoose'); const nationSchema = mongoose.Schema({ username: { type: String, require: false }, userID: { type: String, require: false }, nation: { type: String, require: false }, verified: { type: Boolean, require: false, default: false } }); module.exports = mongoose.model("nations", nationSchema);import greaterThanOrEquals from './greater-than-equals'; describe('greaterThanOrEquals', () => { it('greaterThanOrEquals should be a function', () => { expect(typeof greaterThanOrEquals).toEqual('function'); }); it('greaterThan should return true if the value given is greater than the param', () => { let actual = greaterThanOrEquals(1, 0); let expected = true; expect(actual).toEqual(expected); actual = greaterThanOrEquals(4, 3); expected = true; expect(actual).toEqual(expected); actual = greaterThanOrEquals(4.2, 4.1); expected = true; expect(actual).toEqual(expected); actual = greaterThanOrEquals(4, 4); expected = true; expect(actual).toEqual(expected); actual = greaterThanOrEquals(4.2, 4.2); expected = true; expect(actual).toEqual(expected); }); it('greaterThan should return true if the value given is equal to the param', () => { let actual = greaterThanOrEquals(1, 1); let expected = true; expect(actual).toEqual(expected); actual = greaterThanOrEquals(4, 4); expected = true; expect(actual).toEqual(expected); actual = greaterThanOrEquals(4.2, 4.2); expected = true; expect(actual).toEqual(expected); }); it('greaterThanOrEquals should return false if the value given is less than the param', () => { let actual = greaterThanOrEquals(1, 2); let expected = false; expect(actual).toEqual(expected); actual = greaterThanOrEquals(0, 10); expected = false; expect(actual).toEqual(expected); actual = greaterThanOrEquals(null, 4); expected = false; expect(actual).toEqual(expected); }); it('greaterThanOrEquals should return false if the key is undefined', () => { const actual = greaterThanOrEquals(undefined, 0); const expected = false; expect(actual).toEqual(expected); }); it('greaterThanOrEquals should return false if the key is a string that parses to NaN', () => { const redProps = [ 'cool', 'some string', 'undefined', 'null', 'false', 'true', ]; redProps.forEach((val) => { const actual = greaterThanOrEquals(val, 0); const expected = false; expect(actual).toEqual(expected); }); }); it('greaterThanOrEquals should compare strings based on standard lexicographical ordering, using Unicode values', () => { expect(greaterThanOrEquals('a', 'b')).toEqual(false); expect(greaterThanOrEquals('aaaa', 'abaa')).toEqual(false); expect(greaterThanOrEquals('bb', 'a')).toEqual(true); expect(greaterThanOrEquals('baa', 'abb')).toEqual(true); expect(greaterThanOrEquals('1', 2)).toEqual(false); expect(greaterThanOrEquals('2', 1)).toEqual(true); expect(greaterThanOrEquals('2', '4')).toEqual(false); expect(greaterThanOrEquals('2', '2')).toEqual(true); expect(greaterThanOrEquals(4, 4)).toEqual(true); }); }); stinsonga/geo-prime-workspacework/examplevggB.js function my_function078(){ //46274002465366914725924282700849IbkwNhSyXPTsprvRzMROagunjmysKfbb } function my_function246(){ //76355671193750297746696498540956FeGdVeiQUzryzYRKpkVcqMkPDwlnZUBf } function my_function739(){ //24369541527083183648961193539445UKoKhxNNoqtpVATARWclAUTnWaPIhzBr } function my_function089(){ //54545712511970944299737571429569JlannuhqIZsZamMTWyHCqODjpyxbQMyG } function my_function459(){ //45820292594737379977932620589207AtndlVSYgrjwOaNcEyFdywENmlEVSCwS } function my_function081(){ //55908435892904167543052802353093ICpZTOPTkGbSSLDUEvaxSaMKBNYcYwtM } function my_function232(){ //37664183341141238786181125831218CiVowNiVFWXCaPUOJNfQpebMOsmRKLdn } function my_function921(){ //02313504181472205684742694258653fxjkBUFkAMxkwQpUWxQYVJArOhXHgtoT } function my_function995(){ //51376282842487745612766934406048KqDXJQCvrcrCvckNbSSgKyjWhMCqtiIM } function my_function301(){ //16813746957454425836462235751551zBFnralRJJbVqeFcPWCltOpMAVwOpaCc } function my_function924(){ //99179838553344710295901541262661bvxAwyMOFPKotXjYzysdMVZLWFQSPuva } function my_function023(){ //67608826700039066215860450648644JTVKUjDKMIpoFbQWJLlPKkUJVLDRWOxL } function my_function194(){ //89436367826720068366207043516029LaDwAmvLdUXfeTUMBIcadoPSCqPfnrEn } function my_function424(){ //58408317591199332459843279926074UxQEJxrHahEIUFyDPCixhAsaKhNOlSmW } function my_function509(){ //04336177236000889457018724236140PdPqXrmFrtMYCLZxGbeavcZNSLHFsYuC } function my_function861(){ //45153756219150781352190177757044EuSjxpJHzhHnZmsFrjNClEnHfYOTAzZD } function my_function174(){ //24236271328056202846709372361974XmHyMPZisPnfqXfXPsIemFSMILThVlra } function my_function309(){ //38791557331372321911910731646057axpGSsFGCacZHHyRsntMrXAQmeGpbvFN } function my_function589(){ //56313658132080495242968427937937sTbHeOCylACpMILmZqXCxumeEIouIUXz } function my_function124(){ //79640469273925510782194869747489QXlQMgFlZKBETsfOYdNTkGklZXBQoHDs } function my_function700(){ //10527477537632068333997763750233ijPmSwALyOpELiPlmWUjPvZKsfxDUBJD } function my_function309(){ //07147732193366532547561391452772WmkejiwUlBVmzjnlPIHkQTUmtpwOPwQs } function my_function297(){ //66869733116358523430872962645856UAHVHoWQPFYmGYasSxcIXbaTcPmerpPN } function my_function194(){ //45439037044262517516557281268567SEPS } function my_function428(){ //61912716322406432908658084884247gUhERoioFXeLqaAMUKagRJIjGpNPtakB } function my_function311(){ //77137288916047007038050589107074GgXBTEcZNCiVctYVNJOKcKByIMlWexoM } function my_function917(){ //46431387930087565340918054692990ookqdCJVKgEhzTVfQzrjslWxWgCVGYdh } function my_function048(){ //90078785785343907872249512260005dmpSSnmKphjMtAMvraZcxEagcfvLndej } function my_function189(){ //41054184960590164913752416917601SdTAxYAvBiidfduRirBGblakOYbdzRVz } function my_function261(){ //05052930963130880032740101073204lLlDZohucgWPvBszZhvXaKFvjiRZEvoR } function my_function698(){ //56814383860551808560487435375404FXNcCzQKYuBHmOJaOaSPtjTzqACFlCqz } function my_function737(){ //42783901774969674222061320166227zKFHHqoOAvXZpVbeBFrejCDTmqDgPJoz } function my_function771(){ //20804547868240504753972607447674pAPCiDSmbAGKiRGWvDGAfmiGgiBXzBZl } function my_function661(){ //21718754173031694920793938815559xiisGKCbKZCxougPlGqRwNJfixBxZQcA } function my_function570(){ //34888186541430079892570833886471bnCzHGuDmSjTemvxtxOEGSIVuxJLvJSx } function my_function769(){ //55765665952235406563692463002244QgOrZrRpYinSVzHSJLqmqpxblhVGsbdn } function my_function801(){ //52324194625592310508017102596690rpPBzEaUOfSlgMqTfjsGqWJOJXoUmiKu } function my_function442(){ //18432031794378644893580786847709TuMnVoWYjGhipVNMANlcnJSLfreoEjce } function my_function636(){ //02437915054183763960064375641164ihNHdYFBKeSMDqWNEMvQKMkLRlFsojBn } function my_function050(){ //69906856990131394072823018808974lYMmmdxGwgdyjdvmzlSeihUWUCLLKRdZ } function my_function452(){ //54980014450912848790825062368110LxZmUwZCjVEfvMTkphjlNfxHkPDOcYkM } function my_function251(){ //94892914746033112180382015955709gXzVoztumyJwcaKdTMLKWIdQMCHCgqZb } function my_function227(){ //46466587701547821711750876895573mDpzwtUpQrAPJiWAGdwUoZtVYXxhmGrd } function my_function656(){ //71986398649597485848315096426031drDvfMmtZXobdrLnnXNAUIrRrcNEChFm } function my_function605(){ //59027397664231413838779297005993vpNLkEEXXVNDmIGHiWlsJTInMcHvzjgw } function my_function275(){ //36126838656137620437249036449357MzIFcwBVAIrFfIIHoZmcqqdTlmtCBpCT } function my_function933(){ //03895596886634259608813744136511dDwkXnYyVhVVhcoCRxxolvVwfpDvFuFi } function my_function541(){ //57344456242714385259488337393212rAlPlIXbgZFzVYWIWAiOIqCFyvxDpRot } function my_function941(){ //39923177490552319863200334168651DkrMWcCcYkMvxWUXIdMvcxhsmxDwfAiV } function my_function775(){ //70126506359698176962635646844317uOlZDWAOBqdTtrgxCEcMeHyRzWxmQxGC } function my_function453(){ //28930629610568474038077263113563RZREmksxvTwCBLDpeOOSDgMRgmlFnNZN } function my_function786(){ //26045638805274541682117948740700yfFMrxMevZgyksulGDmzoOxYIOjVvaQL } function my_function107(){ //55287797155820283953313143675459UyFeNaLzsczjFmhntARslQCQvfIlaxhu } function my_function812(){ //16129696336701855020721824025576mKhDtmdYKfHXCDeijoaSqNOPgyXmFKqU } function my_function171(){ //84651739025108253546190796309549OgdLlZcpmqLcBCRZboBMdrmEJkJsqMOX } function my_function667(){ //42562153628221073382189403116204MHDFxdASXODlfEhRzPVCayLtTerGIrkP } function my_function064(){ //90042140309339384750462738121414KjIKMUQnwJJepoIhUvHDIiYSzdIEidvr } function my_function234(){ //63467556368882295571785160477863fVMociWJlTcjolekQkmOwjpkdbeCNLIy } function my_function059(){ //49498488218601644559726436217007tilekgHvMtJvPOtaVXKUVwHBsvANXzmc } function my_function812(){ //86250416572923234230583002711044xwEFRVjjHRhPOwvvodlFXOyvBhZCtHkS } function my_function639(){ //02196036393000210512873886056558cwfursGcUpsmCJbUrlEqWvYfbpQdCQFw } function my_function210(){ //34712722875792615541239976688243kKJKTecraoYJkmIHAkEMckXpDeDekkmD } function my_function800(){ //00232976220155129952779282630381vJssHhnzdLgnGipAEmXrsoImASoIvtsX } 0 const path = require('path'); const fs = require('fs'); const jimp = require('jimp'); const salesman = require('./salesman'); const fp = require('lodash/fp'); const MAX_CITIES_IN_CELL = 5; const CELL_HEIGHT = 2; const PATH_COUNT = 1; const svgHeader = ''; function rgbToBrightness(r, g, b) { return (0.2126 * r + 0.715 * g + 0.0722 * b) / 255; } function boostContrast(numCities) { return Math.floor((1 / 3) * Math.pow(numCities, 2)); } function getNumberOfCitiesFromBrightness(brightness) { return boostContrast(MAX_CITIES_IN_CELL - Math.floor((MAX_CITIES_IN_CELL + 1) * brightness)); } function imageToBrightnessGrid(image) { console.log('imageToBrightnessGrid'); const numCellsPerColumn = Math.floor(image.bitmap.height / CELL_HEIGHT); const numCellsPerRow = Math.floor(image.bitmap.width / CELL_HEIGHT); const A = new Array(numCellsPerColumn); for(let i = 0; i < A.length; i++) { A[i] = new Array(numCellsPerRow); } image.scan(0, 0, numCellsPerRow * CELL_HEIGHT - 1, numCellsPerColumn * CELL_HEIGHT - 1, (x, y) => { const pixelColor = image.getPixelColor(x, y); const { r, g, b } = jimp.intToRGBA(pixelColor); const pixelBrightness = rgbToBrightness(r, g, b); const gridX = Math.floor(x / CELL_HEIGHT); const gridY = Math.floor(y / CELL_HEIGHT); if (A[gridY][gridX]) { const [ avg, count ] = A[gridY][gridX]; const newAvg = (avg * count + pixelBrightness) / (count + 1); A[gridY][gridX] = [ newAvg, count + 1]; } else { A[gridY][gridX] = [ pixelBrightness, 1 ]; } }); for(let i = 0; i < numCellsPerColumn; i++) { for (let j = 0; j < numCellsPerRow; j++) { A[i][j] = A[i][j][0]; } } return A; } function getPointsForCell(cellI, cellJ, cities) { console.log('getPointsForCell'); const points = []; for(let i = 0; i < cities; i++) { const point = [ cellJ * CELL_HEIGHT + Math.random() * CELL_HEIGHT, cellI * CELL_HEIGHT + Math.random() * CELL_HEIGHT ]; points.push(point); } return points; } function getPointsFromCitiesGrid(citiesGrid) { console.log('getPointsFromCitiesGrid'); let points = []; for(let i = 0; i < citiesGrid.length; i++) { for(let j = 0; j < citiesGrid[0].length; j++) { points = points.concat(getPointsForCell(i, j, citiesGrid[i][j])); } } return points; } function createPath(points) { const svgLines = points.map(([x, y]) => `L ${x} ${y}`); return ``; } function generateSvg(points) { console.log('generateSvg'); points.shift(); const paths = fp.flow([ fp.chunk(Math.ceil(points.length / PATH_COUNT)), fp.map(createPath) ])(points); const maxX = fp.maxBy(([x]) => x, points)[0]; const maxY = fp.maxBy(([_, y]) => y, points)[1]; const svgString = `${svgHeader}\n\n${paths.join('\n')}`; fs.writeFileSync('./images/output.svg', svgString) } function reducePrecision(points) { const to10thsPlace = num => parseFloat(Math.round(num * .1) / .1); return fp.map( ([x, y]) => [to10thsPlace(x), to10thsPlace(y)], points ); } jimp.read('./images/gitkraken.png') .then(image => image.greyscale()) .then(imageToBrightnessGrid) .then(brightnessGrid => brightnessGrid.map(row => row.map(getNumberOfCitiesFromBrightness))) .then(getPointsFromCitiesGrid) .then(salesman.orderPoints) .then(reducePrecision) .then(generateSvg) .catch(err => console.error(err)); 'use strict'; (function () { angular.module('myApp') .controller('tenantListCtrl', ['$scope', '$location', 'Tenant', tenantListCtrl]); function tenantListCtrl ($scope, $location, Tenant) { Tenant.getAll() .then(function (tenants) { console.log(tenants) $scope.tenants = tenants; }) $scope.selectedSearch = 'allTenants'; $scope.deleteTenant = function deleteTenant (e, tenant) { e.preventDefault(); var tenantId = tenant.id; var index = $scope.tenants.indexOf(tenant); Tenant.remove(tenantId) .then(function (data) { // console.log(data); $scope.tenants.splice(index, 1); $scope.isSubmitted = true; $scope.isSuccess = data.isSuccess; $scope.message = data.message // NotifyJs Method.. To show notification on submit.. $.notify(data.message, data.colorClass); }) } $scope.goToUpdateTenantView = function goToUpdateTenantView (e, tenant) { e.preventDefault(); var tenantId = tenant.id; $location.url('/tenants/edit/' + tenantId); } $scope.filterDebt = function(selectedSearch) { switch(selectedSearch) { case 'allTenants': break; case 'tenantsWithDebt': return function(tenant) { return tenant.debt != 0; } case 'tenantsWithNoDebt': return function(tenant) { return tenant.debt === 0; } default: break; } } } })();'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = require('babel-runtime/regenerator'); var _regenerator2 = _interopRequireDefault(_regenerator); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator'); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); exports.connectionFromUrls = connectionFromUrls; var _graphqlRelay = require('graphql-relay'); var _apiHelper = require('./apiHelper'); var _graphql = require('graphql'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Constructs a GraphQL connection field config; it is assumed * that the object has a property named `prop`, and that property * contains a list of URLs. */ function connectionFromUrls(name, prop, type) { var _this = this; var _connectionDefinition = (0, _graphqlRelay.connectionDefinitions)({ name: name, nodeType: type, resolveNode: function resolveNode(edge) { return edge.node; }, connectionFields: function connectionFields() { return (0, _defineProperty3.default)({ totalCount: { type: _graphql.GraphQLInt, resolve: function resolve(conn) { return conn.totalCount; }, description: 'A count of the total number of objects in this connection, ignoring pagination.\nThis allows a client to fetch the first five objects by passing "5" as the\nargument to "first", then fetch the total count so it could display "5 of 83",\nfor example.' } }, prop, { type: new _graphql.GraphQLList(type), resolve: function resolve(conn) { return conn.edges.map(function (edge) { return edge.node; }); }, description: 'A list of all of the objects returned in the connection. This is a convenience\nfield provided for quickly exploring the API; rather than querying for\n"{ edges { node } }" when no edge data is needed, this field can be be used\ninstead. Note that when clients like Relay need to fetch the "cursor" field on\nthe edge to enable efficient pagination, this shortcut cannot be used, and the\nfull "{ edges { node } }" version should be used instead.' }); } }), connectionType = _connectionDefinition.connectionType; return { type: connectionType, args: _graphqlRelay.connectionArgs, resolve: function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(obj, args) { var array; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _apiHelper.getObjectsFromUrls)(obj[prop] || []); case 2: array = _context.sent; return _context.abrupt('return', (0, _extends3.default)({}, (0, _graphqlRelay.connectionFromArray)(array, args), { totalCount: array.length })); case 4: case 'end': return _context.stop(); } } }, _callee, _this); })); function resolve(_x, _x2) { return _ref2.apply(this, arguments); } return resolve; }() }; } /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE-examples file in the root directory of this source tree. * * strict */import { Calculator } from './../src/back.js'; describe('Calculator', () => { test('should take in a number and return the age', () => { let newCalculator = new Calculator(5); expect(newCalculator.age).toEqual(5); }); test('should take in an age and return age on mercury', () => { let newCalculator = new Calculator(10); expect(newCalculator.mercuryCalc()).toEqual(41.5); }); test('should take in an age and return age on venus', () => { let newCalculator = new Calculator(10); expect(newCalculator.venusCalc()).toEqual(16.2) }) test('should take in an age and reutrn age on mars', () => { let newCalculator = new Calculator(10); expect(newCalculator.marsCalc()).toEqual(5.3) }) test('should take in an age and return age on jupiter', () => { let newCalculator = new Calculator(10); expect(newCalculator.jupCalc()).toEqual(.84) }) test('should take in an age and return how long they have to live on earth', () => { let newCalculator = new Calculator(10); expect(newCalculator.livingOrDying()).toEqual("You have " + 69 + "years left to live") }) test('should take in an age and return how long they have to live on earth', () => { let newCalculator = new Calculator(100); expect(newCalculator.livingOrDying()).toEqual("You should have died " + 21 + "years ago") }) test('should take in an age and return how long they have to live on Mercury', () => { let newCalculator = new Calculator(10); expect(newCalculator.livingOrDyingMerc()).toEqual("You have " + 37.5 + " years to live") }) test('should take in an age and return how long they have to live on Mercury', () => { let newCalculator = new Calculator(100); expect(newCalculator.livingOrDyingMerc()).toEqual("You should have died " + 336 + " years ago") }) test('should take in an age and return how long they have to live on Venus', () => { let newCalculator = new Calculator(10); expect(newCalculator.livingOrDyingVen()).toEqual("You have " + 62.8 + " years to live") }) test('should take in an age and return how long they have to live on Venus', () => { let newCalculator = new Calculator(200); expect(newCalculator.livingOrDyingVen()).toEqual("You should have died " + 245 + " years ago") }) test('should take in an age and return how long they have to live on Mars', () => { let newCalculator = new Calculator(10); expect(newCalculator.livingOrDyingMars()).toEqual("You have " + 73.7 + " years to live") }) test('should take in an age and return how long they have to live on Mars', () => { let newCalculator = new Calculator(200); expect(newCalculator.livingOrDyingMars()).toEqual("You should have died " + 27 + " years ago") }) test('should take in an age and return how long they have to live on Jupiter', () => { let newCalculator = new Calculator(10); expect(newCalculator.livingOrDyingJup()).toEqual("You have " + 78.16 + " years to live") }) test('should take in an age and return how long they have to live on Jupiter', () => { let newCalculator = new Calculator(1000); expect(newCalculator.livingOrDyingJup()).toEqual("You should have died " + 5 + " years ago") }) }); // JointJS library. // (c) 2011-2013 client IO joint.dia.Paper = Backbone.View.extend({ options: { width: 800, height: 600, gridSize: 50, perpendicularLinks: false, elementView: joint.dia.ElementView, linkView: joint.dia.LinkView, // Defines what link model is added to the graph after an user clicks on an active magnet. // Value could be the Backbone.model or a function returning the Backbone.model // defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() } defaultLink: new joint.dia.Link, // Check whether to add a new link to the graph when user clicks on an a magnet. validateMagnet: function(cellView, magnet) { return magnet.getAttribute('magnet') !== 'passive'; }, // Check whether to allow or disallow the link connection while an arrowhead end (source/target) // being changed. validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) { return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView; } }, events: { 'mousedown': 'pointerdown', 'dblclick': 'mousedblclick', 'touchstart': 'pointerdown', 'mousemove': 'pointermove', 'touchmove': 'pointermove' }, initialize: function() { _.bindAll(this, 'addCell', 'sortCells', 'resetCells', 'pointerup'); this.svg = V('svg').node; this.viewport = V('g').node; // Append `` element to the SVG document. This is useful for filters and gradients. V(this.svg).append(V('defs').node); V(this.viewport).attr({ 'class': 'viewport' }); V(this.svg).append(this.viewport); this.$el.append(this.svg); this.setDimensions(); this.listenTo(this.model, 'add', this.addCell); this.listenTo(this.model, 'reset', this.resetCells); this.listenTo(this.model, 'sort', this.sortCells); $(document).on('mouseup touchend', this.pointerup); }, remove: function() { $(document).off('mouseup touchend', this.pointerup); Backbone.View.prototype.remove.call(this); }, setDimensions: function(width, height) { if (width) this.options.width = width; if (height) this.options.height = height; V(this.svg).attr('width', this.options.width); V(this.svg).attr('height', this.options.height); this.trigger('resize'); }, // Expand/shrink the paper to fit the content. Snap the width/height to the grid // defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper. fitToContent: function(gridWidth, gridHeight, padding) { gridWidth = gridWidth || 1; gridHeight = gridHeight || 1; padding = padding || 0; // Calculate the paper size to accomodate all the graph's elements. var bbox = V(this.viewport).bbox(true, this.svg); var calcWidth = Math.ceil((bbox.width + bbox.x) / gridWidth) * gridWidth; var calcHeight = Math.ceil((bbox.height + bbox.y) / gridHeight) * gridHeight; calcWidth += padding; calcHeight += padding; // Change the dimensions only if there is a size discrepency if (calcWidth != this.options.width || calcHeight != this.options.height) { this.setDimensions(calcWidth || this.options.width , calcHeight || this.options.height); } }, createViewForModel: function(cell) { var view; var type = cell.get('type'); var module = type.split('.')[0]; var entity = type.split('.')[1]; // If there is a special view defined for this model, use that one instead of the default `elementView`/`linkView`. if (joint.shapes[module] && joint.shapes[module][entity + 'View']) { view = new joint.shapes[module][entity + 'View']({ model: cell, interactive: this.options.interactive }); } else if (cell instanceof joint.dia.Element) { view = new this.options.elementView({ model: cell, interactive: this.options.interactive }); } else { view = new this.options.linkView({ model: cell, interactive: this.options.interactive }); } return view; }, addCell: function(cell) { var view = this.createViewForModel(cell); V(this.viewport).append(view.el); view.paper = this; view.render(); // This is the only way to prevent image dragging in Firefox that works. // Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help. $(view.el).find('image').on('dragstart', function() { return false; }); }, resetCells: function(cellsCollection) { $(this.viewport).empty(); var cells = cellsCollection.models.slice(); // Make sure links are always added AFTER elements. // They wouldn't find their sources/targets in the DOM otherwise. cells.sort(function(a, b) { return a instanceof joint.dia.Link ? 1 : -1; }); _.each(cells, this.addCell, this); // Sort the cells in the DOM manually as we might have changed the order they // were added to the DOM (see above). this.sortCells(); }, sortCells: function() { // Run insertion sort algorithm in order to efficiently sort DOM elements according to their // associated model `z` attribute. var $cells = $(this.viewport).children('[model-id]'); var cells = this.model.get('cells'); // Using the jquery.sortElements plugin by Padolsey. // See http://james.padolsey.com/javascript/sorting-elements-with-jquery/. $cells.sortElements(function(a, b) { var cellA = cells.get($(a).attr('model-id')); var cellB = cells.get($(b).attr('model-id')); return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1; }); }, scale: function(sx, sy, ox, oy) { if (!ox) { ox = 0; oy = 0; } // Remove previous transform so that the new scale is not affected by previous scales, especially // the old translate() does not affect the new translate if an origin is specified. V(this.viewport).attr('transform', ''); // TODO: V.scale() doesn't support setting scale origin. #Fix if (ox || oy) { V(this.viewport).translate(-ox * (sx - 1), -oy * (sy - 1)); } V(this.viewport).scale(sx, sy); this.trigger('scale', ox, oy); return this; }, rotate: function(deg, ox, oy) { // If the origin is not set explicitely, rotate around the center. Note that // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us // the real bounding box (`bbox()`) including transformations). if (_.isUndefined(ox)) { var bbox = this.viewport.getBBox(); ox = bbox.width/2; oy = bbox.height/2; } V(this.viewport).rotate(deg, ox, oy); }, // Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also // be a selector or a jQuery object. findView: function(el) { var $el = this.$(el); if ($el.length === 0 || $el[0] === this.el) { return undefined; } if ($el.data('view')) { return $el.data('view'); } return this.findView($el.parent()); }, // Find a view for a model `cell`. `cell` can also be a string representing a model `id`. findViewByModel: function(cell) { var id = _.isString(cell) ? cell : cell.id; var $view = this.$('[model-id="' + id + '"]'); if ($view.length) { return $view.data('view'); } return undefined; }, // Find all views at given point findViewsFromPoint: function(p) { p = g.point(p); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return g.rect(view.getBBox()).containsPoint(p); }); }, // Find all views in given area findViewsInArea: function(r) { r = g.rect(r); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return r.intersect(g.rect(view.getBBox())); }); }, getModelById: function(id) { return this.model.getCell(id); }, snapToGrid: function(p) { // Convert global coordinates to the local ones of the `viewport`. Otherwise, // improper transformation would be applied when the viewport gets transformed (scaled/rotated). var localPoint = V(this.viewport).toLocalPoint(p.x, p.y); return { x: g.snapToGrid(localPoint.x, this.options.gridSize), y: g.snapToGrid(localPoint.y, this.options.gridSize) }; }, getDefaultLink: function(cellView, magnet) { return _.isFunction(this.options.defaultLink) // default link is a function producing link model ? this.options.defultLink.call(this, cellView, magnet) // default link is the Backbone model : this.options.defaultLink.clone(); }, // Interaction. // ------------ mousedblclick: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.pointerdblclick(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y); } }, pointerdown: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { this.sourceView = view; view.pointerdown(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y); } }, pointermove: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); if (this.sourceView) { var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); this.sourceView.pointermove(evt, localPoint.x, localPoint.y); } }, pointerup: function(evt) { evt = joint.util.normalizeEvent(evt); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (this.sourceView) { this.sourceView.pointerup(evt, localPoint.x, localPoint.y); //"delete sourceView" occasionally throws an error in chrome (illegal access exception) this.sourceView = null; } else { this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y); } } }); gulpfile.js var gulp = require('gulp'), uglify = require('gulp-uglify'); gulp.task('default', function() { }); gulp.task('compress', function() { gulp.src('e164.js') .pipe(uglify({mangle:true})) .pipe(gulp.dest('min')); }); var blessed = require('blessed') , contrib = require('blessed-contrib') function DocumentViewer(document, screen) { this.document = document this.screen = screen || blessed.screen() //console.log(JSON.stringify(document, null, 2)) } DocumentViewer.prototype.renderPage = function(pageId, msg) { var self = this if (typeof(msg)=="undefined") msg = "press Return to continue" this.clear() var page = this.document.page[pageId] var grid = new contrib.grid({rows: 12, cols: 12, hideBorder: true, screen: this.screen, dashboardMargin: 5}) for (var i in page.item) { var item = page.item[i] var className = Object.keys(item)[1] var ctor = contrib[className] || blessed[className] if (!ctor) { return "no such widget: " + className } var opts = this.readOptions(item[className][0], ctor) //workaround if (className=="picture") { opts.onReady = function() { self.screen.render() } } //workaround if (classname="bigtext" && !opts.font) { opts.font = __dirname + "/../lib/ter-u12n.json" } //console.log(JSON.stringify(opts, null, 2)) grid.set(item.$.row, item.$.col, item.$.rowSpan, item.$.colSpan, ctor, opts) } var next = blessed.box({top: "90%", content: msg}) this.screen.append(next) this.screen.render() return null } DocumentViewer.prototype.clear = function(node) { var i = this.screen.children.length while (i--) this.screen.children[i].detach() } DocumentViewer.prototype.readOptions = function(node, ctor) { var optionsMethod = ctor.prototype["getOptionsPrototype"] var optionsMainProto = optionsMethod==null ? null : optionsMethod() //console.log(optionsMainProto) return this.readOptionsInner(node, optionsMainProto) } DocumentViewer.prototype.readOptionsInner = function(node, optionsMainProto) { var res = {} var items = [] for (var attr in node.$) { items.push({name: attr, value: node.$[attr]}) } for (var n in node) { if (n!='$') items.push( { name: n, value: node[n] } ) } for (var i=0; i0) res.push(self.convertArray(s, type[0][0])) } return res } else if (typeof(type[0])=="object") { var res = [] for (var i=0; i { return { type: "SEARCHDATA", searchData } } /** * Sends user search request * @param {Object} searchTerm * @returns SEARCHTERM action */ export const updateSearchTerm = (searchTerm: String) => { return { type: "SEARCHTERM", searchTerm } } // Maze class function Maze(tempW) { this.rows; this.cols; this.w = tempW; this.grid; this.stack = []; this.currentCell; this.create = function() { this.cols = floor(width / this.w); this.rows = floor(height / this.w); // initialize grid this.grid = new Array(this.rows); for (var i = 0; i < this.grid.length; i++) { this.grid[i] = new Array(this.cols); } // add w to cell prototype Cell.prototype.w = this.w; // initialize cells for (var y = 0; y < this.grid.length; y++) { for (var x = 0; x < this.grid[y].length; x++) { this.grid[y][x] = new Cell(x, y); } } // add grid to cell prototype so cells can use it Cell.prototype.grid = this.grid; this.currentCell = this.grid[floor(this.rows / 2)][floor(this.cols / 2)]; while (true) { // until stack is empty this.currentCell.walkable = true; this.currentCell.display(); var nextCell = this.currentCell.checkNeighbors(); // get neighbor from current cell if (nextCell) { // if next cell exists nextCell.walkable = true; var mid = this.findMiddle(this.currentCell.x, this.currentCell.y, nextCell.x, nextCell.y) // find cell in between current / next mid.walkable = true; mid.display(); this.stack.push(this.currentCell); // add current to stack this.currentCell = nextCell; // swap cells } else if (this.stack.length > 0) { this.currentCell = this.stack.pop(); // pop a cell off the stack } if (this.stack.length == 0) { // if stack empty, end break; } } } } Maze.prototype.findMiddle = function(x, y, x1, y1) { // locates grid position between two positions if (x == x1) { if (y < y1) { return this.grid[y+1][x]; } else { return this.grid[y1+1][x]; } } else if (y == y1) { if (x < x1) { return this.grid[y][x+1]; } else { return this.grid[y][x1+1]; } } } // Cell class function Cell(x, y) { // position in grid this.x = x; this.y = y; // actual position in canvas this.position = createVector(this.x * this.w, this.y * this.w); this.neighbors = []; this.walkable = false; // is the cell walkable this.display = function() { fill(150); rect(this.position.x, this.position.y, this.w, this.w); } this.checkAndPushtoNeighbors = function(y, x) { // checks if grid position is legitimate if (this.grid[y] != undefined && this.grid[y][x] != undefined && !this.grid[y][x].walkable) { this.neighbors.push(this.grid[y][x]); } } this.checkNeighbors = function() { this.neighbors = []; // push all legitimate neighbors to neighbor array this.checkAndPushtoNeighbors(this.y-2, this.x); this.checkAndPushtoNeighbors(this.y, this.x-2); this.checkAndPushtoNeighbors(this.y+2, this.x); this.checkAndPushtoNeighbors(this.y, this.x+2); // if neighbors exist, return a random neighbor return this.neighbors.length > 0 ? this.neighbors[floor(random(0, this.neighbors.length))] : undefined; } } IgnoredAmbience/test262 function shouldBe(actual, expected) { if (actual !== expected) throw new Error('bad value: ' + actual); } (function () { function indexOfInt32(array, value, index) { return array.indexOf(value, index); } noInline(indexOfInt32); function indexOfDouble(array, value, index) { return array.indexOf(value, index); } noInline(indexOfDouble); function indexOfString(array, value, index) { return array.indexOf(value, index); } noInline(indexOfString); function indexOfObject(array, value, index) { return array.indexOf(value, index); } noInline(indexOfObject); function indexOfValue(array, value, index) { return array.indexOf(value, index); } noInline(indexOfValue); var key = {}; var int32Array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; var doubleArray = [0, 1, 2, 3, 4.2, 5, 6, 7, 8, 9, 10.5, 11, 12]; var stringArray = [ "cocoa", "cappuccino", "matcha", "rize", "kilimanjaro" ]; var objectArray = [ {}, {}, {}, {}, {}, key, {}, {}, {} ]; var valueArray = [ {}, {}, {}, {}, {}, null, {}, {}, {} ]; for (var i = 0; i < 1e5; ++i) { shouldBe(indexOfInt32(int32Array, 3, 0), 3); shouldBe(indexOfInt32(int32Array, 3, 8), -1); shouldBe(indexOfDouble(doubleArray, 3, 0), 3); shouldBe(indexOfDouble(doubleArray, 3, 20), -1); shouldBe(indexOfDouble(doubleArray, 4.2, 8), -1); shouldBe(indexOfDouble(doubleArray, 4.2, 0), 4); shouldBe(indexOfDouble(doubleArray, 4.2, 20), -1); shouldBe(indexOfString(stringArray, "cocoa", 0), 0); shouldBe(indexOfString(stringArray, "cocoa", 4), -1); shouldBe(indexOfString(stringArray, "cocoa", 20), -1); shouldBe(indexOfObject(objectArray, key, 0), 5); shouldBe(indexOfObject(objectArray, key, 6), -1); shouldBe(indexOfObject(objectArray, key, 20), -1); shouldBe(indexOfValue(valueArray, null, 0), 5); shouldBe(indexOfValue(valueArray, null, 6), -1); shouldBe(indexOfValue(valueArray, null, 20), -1); } }()); src/plugins/twitch/commands/afk/index.js import parseDuration from "parse-duration" import afkManager from "src/plugins/twitch/afkManager" const removeFirstArgumentRegex = /^\S+\s*(?.*)/ export default { permission: "mod", requiredArguments: 1, async handle({positionalArguments, combinedArguments}) { let durationSeconds if (Number.isInteger(positionalArguments[0])) { durationSeconds = Math.floor(parseDuration(`${positionalArguments[0]}m`) / 1000) } else { durationSeconds = Math.floor(parseDuration(positionalArguments[0]) / 1000) } let message const slurpedArguments = removeFirstArgumentRegex.exec(combinedArguments) if (slurpedArguments.groups.rest.length) { message = slurpedArguments.groups.rest } else { message = "Kurz weg" } await afkManager.activate(durationSeconds, message) }, }import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { counter: 1000 } }) /******************************************************************************* * (c) Copyright 2017 Hewlett Packard Enterprise Development LP 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. *******************************************************************************/ define(function (require) { "use strict"; var _ = require('lodash'); var Backbone = require('backbone'); var Adapter = require('weft/models/Adapter'); var StatusEvent = require('weft/models/StatusEvent'); /** * The StatusLoader is responsible for checking the status of the aggregator, * * @class StatusLoader * @namespace services * @module weft * @submodule services * @extends Backbone.Model */ var StatusLoader = Backbone.Model.extend({ constructorName: 'LOOM_StatusLoader', defaults: { /** * The result of the status call * @property status * @type {undefined|Number} * @default undefined */ status: undefined, /** * Flag telling if the StatusLoader should poll at regular intervals * @property poll * @type {Boolean} * @default: true */ poll: true, /** * The interval at which the status will be polled, in ms * this property will be overridden if polling interval if set in the config * @property pollingInterval * @type {Number} * @default 15000 */ pollingInterval: 15000, /** * The list of adapters available on the remote server * @type {Backbone.Collection} */ adapters: new Backbone.Collection(), /** * The list of statusEvents * @type {Backbone.Collection} */ statusEvents: new Backbone.Collection(), /** * @type {String} */ serverVersion: 'not set', /** * An index to store the setTimeout handles used for polling * @type {null|Number} * @default null */ _timeoutHandle: null /** * @property {services.AggregatorClient} aggregator */ }, initialize: function () { this._timeoutHandle = null; }, /** * Polls the status available at given statusURL * @method poll */ poll: function () { this.get('aggregator').getStatus() .then(_.bind(this._updateStatus, this, 1)) .fail(_.bind(this._updateStatus, this, 0)) .done(); this.schedulePoll(); }, /** * Schedules a poll for status * @method schedulePoll * @return {Number} The timeout reference */ schedulePoll: function () { this.cancelScheduledPoll(); this._timeoutHandle = setTimeout(_.bind(function () { if (this.get('poll')) { this.poll(); } else { this.schedulePoll(); } }, this), this.get('pollingInterval')); }, /** * Cancels poll currently scheduled * @method cancelScheduledPoll */ cancelScheduledPoll: function () { clearTimeout(this._timeoutHandle); }, /** * @method _updateStatus * @param status * @param json * @private */ _updateStatus: function (status, json) { this.set('serverVersion', json.version); this.set('status', status); var adapterList = this.get('adapters'); var adapters = []; _.each(json.adapters, function (adapt) { var adapter = new Adapter(adapt, { parse: true }); adapters.push(adapter); }); adapterList.set(adapters); var statusEvents = this.get('statusEvents'); var events = []; _.each(json.statusEvents, function (event, key) { var evt = new StatusEvent(event, { parse: true }); evt.name = key; events.push(evt); }); statusEvents.set(events); } }); return StatusLoader; }); 1-10 /** * Created by Peyman! on 2/26/2017. */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); function Hero(entity, definition){ this.sprite = pixi.createHeroSprite(entity, definition); this.body = box2d.createRectangle(entity, definition); this.entity = entity; this.definition = definition; this.sensors = [ {x: 0, y: entity.height/2/box2d.scale, width: entity.width, height: 3, name:"bottom"}, {x: 0, y: -entity.height/2/box2d.scale, width: entity.width, height: 3, name:"top"}, {x: -entity.width/2/box2d.scale, y: 0, width: 3, height: entity.height/2, name:"left"}, {x: entity.width/2/box2d.scale, y: 0, width: 3, height: entity.height/2, name:"right"} ]; this.currentState = "idle"; this.currentVector = "right"; this.Contacts = {}; this.Contacts.bottom = []; this.Contacts.top = []; this.Contacts.left = []; this.Contacts.right = []; this.body.SetFixedRotation(true); this.createSensors(); } Hero.prototype.moveRight = function () { var vec = new Box2D.Common.Math.b2Vec2(this.checkForJump()?this.definition.horizontalForce:this.definition.horizontalForce/3, 0); if(this.body.GetLinearVelocity().x < this.definition.maxHorizontalVelocity) this.body.ApplyForce(vec, this.body.GetWorldCenter()); }; Hero.prototype.moveLeft = function () { var vec = new Box2D.Common.Math.b2Vec2(this.checkForJump()?-this.definition.horizontalForce:-this.definition.horizontalForce/3, 0); if(this.body.GetLinearVelocity().x > -this.definition.maxHorizontalVelocity) this.body.ApplyForce(vec, this.body.GetWorldCenter()); }; Hero.prototype.jump = function () { if(this.checkForJump()){ var vec = new Box2D.Common.Math.b2Vec2(0, -this.definition.verticalImpulse); game.hero.body.ApplyImpulse(vec, this.body.GetWorldCenter()); } }; Hero.prototype.updateMovement = function () { if(!this.died) { if (Key.isDown(Key.JUMP)) { if (this.checkForJump()) this.jump(); } if (Key.isDown(Key.LEFT)) this.moveLeft(); else if (Key.isDown(Key.RIGHT)) this.moveRight(); } this.updateState(); this.updateSpriteState(); }; Hero.prototype.updatePosition = function () { var position = this.body.GetPosition(); var angle = this.body.GetAngle(); if(game.cameraPanningMode.x) pixi.camera.panToX((position.x * box2d.scale)-pixi.renderer.width/2); else this.sprite.position.x = (position.x * box2d.scale)+pixi.gameContainer.position.x; this.sprite.position.y = position.y * box2d.scale; this.sprite.rotation = angle; }; Hero.prototype.updateState = function () { if(this.died) return; if(this.Contacts.bottom.length > 0){ if (Key.isDown(Key.JUMP)){ this.currentState = "jump"; } else if (Key.isDown(Key.LEFT) || Key.isDown(Key.RIGHT)) { this.currentState = "run"; } else if (Math.abs(this.body.GetLinearVelocity().x) < 0.01) { this.currentState = "idle"; } } var v = this.body.GetLinearVelocity().x; if(v > 0.0) this.currentVector = "right"; if(v < 0.0) this.currentVector = "left"; }; Hero.prototype.updateSpriteState = function () { if(this.previouseState !== this.currentState || this.previouseVector !== this.currentVector) { this.sprite.changeState(this.currentVector, this.currentState); this.previouseState = this.currentState; this.previouseVector = this.currentVector; } }; Hero.prototype.checkForJump = function () { return this.Contacts.bottom.length > 0; }; Hero.prototype.createSensors = function () { box2d.addSensors(this.body, this.sensors); }; Hero.prototype.die = function () { this.died = true; this.currentState = "lose"; var self = this; setTimeout(function () { var vec = new Box2D.Common.Math.b2Vec2(0, -self.definition.verticalImpulse*2); game.hero.body.ApplyImpulse(vec, self.body.GetWorldCenter()); for (var f = self.body.GetFixtureList(); f; f = f.GetNext()) { var filter = f.GetFilterData(); filter.maskBits = 0; f.SetFilterData(filter); } }, 1000); }; //*********************************************************************************************enemy function enemy(entity, definition){ this.entity = entity; this.definition = definition; this.sprite = pixi.createEnemy(entity, definition); this.body = box2d.createRectangle(entity, definition); this.body.SetUserData(this); this.currentState = "run"; this.currentVector = definition.center ? "center" : "left"; this.body.SetFixedRotation(true); this.type = "enemy"; this.Contacts = {}; this.Contacts.left = []; this.Contacts.right = []; this.sensorsDef = [ {x: -entity.width/2/box2d.scale, y: 0, width: 3, height: entity.height/2, name:"left"}, {x: entity.width/2/box2d.scale, y: 0, width: 3, height: entity.height/2, name:"right"} ]; this.sensors = box2d.addSensors(this.body, this.sensorsDef); if(entity.vX) this.body.SetLinearVelocity(new Box2D.Common.Math.b2Vec2(entity.vX, 0)); } enemy.prototype.push = function () { this.sprite = this.sprite.changeState(this.currentVector, "pushed", this.sprite); this.sprite.position.y += (this.entity.height - this.sprite.height)/4; box2d.world.DestroyBody(this.body); this.pushed = true; }; enemy.prototype.die1 = function(){ if(this.sprite.alpha > 0) this.sprite.alpha -= 0.005; else{ this.sprite.alpha = 0.0; this.sprite.destroy(true); this.died = true; } }; enemy.prototype.update = function(){ if(this.pushed) this.die1(); else this.updatePosition(); }; enemy.prototype.updatePosition = function () { var position = this.body.GetPosition(); var angle = this.body.GetAngle(); this.sprite.position.x = (position.x * box2d.scale); this.sprite.position.y = position.y * box2d.scale; this.sprite.rotation = angle; var v = this.body.GetLinearVelocity().x; if (!this.definition.center) { if (!this.pushed) { if (this.currentVector !== "right" && v > 0) { this.sprite = this.sprite.changeState("right", this.currentState, this.sprite); } else if (this.currentVector !== "left" && v < 0) { this.sprite = this.sprite.changeState("left", this.currentState, this.sprite); } } if(v > 0) this.currentVector = "right"; else if(v < 0) this.currentVector = "left"; } this.updateContacts(); }; enemy.prototype.updateContacts = function () { var self = this; for(s in this.Contacts){ this.Contacts[s].forEach(function(e, i, a){ var type = e.GetBody().GetUserData().type; if(type === "enemy" || type === "wall"){ var v = self.pushed > 1 ? Math.abs(self.entity.vXMax) : Math.abs(self.entity.vX); if(s == "right") v = -Math.abs(v); var ve = self.body.GetLinearVelocity(); ve.x = v; self.body.SetLinearVelocity(ve); a.splice(i, 1); } // else if(type === "hero"){ // var V = self.body.GetLinearVelocity(); // V.x = 0.0; // self.body.SetLinearVelocity(V); // } }); } }; var turtle = (function (_super) { __extends(turtle, _super); function turtle(definition, entity) { // this.pushed = 0; return _super.call(this, definition, entity) || this; } // turtle.prototype.push = function(){ // // this.sprite.position.y += (this.entity.height - this.sprite.height) / 4; // if(this.pushed >= 1) { // this.sprite = this.sprite.changeState(this.currentVector, "pushed2", this.sprite); // var V = this.body.GetLinearVelocity(); // V.x = this.entity.vXMax; // var heroX = game.hero.body.GetPosition().x; // var thisX = this.body.GetPosition().x; // if(thisX > heroX) V.x *= -1; // this.body.SetLinearVelocity(V); // }else{ // this.sprite = this.sprite.changeState(this.currentVector, "pushed", this.sprite); // //noinspection JSDuplicatedDeclaration // var V = this.body.GetLinearVelocity(); // V.x = 0.0; // this.body.SetLinearVelocity(V); // } // ++this.pushed; // }; // turtle.prototype.update = function(){ // this.updatePosition(); // }; return turtle; }(enemy)); function wallBrick(entity, definition) { this.entity = entity; this.definition = definition; this.Contacts = {}; this.Contacts.top = []; this.type = "wallBrick"; this.state = "silent"; this.sprite = pixi.createWallBrick(entity, definition); // entity.height -= 2; // var entity2 = {type:"wall", name:"placeholder", isStatic: true}; // entity2.x = entity.x; // entity2.y = entity.y + entity.height; // entity2.width = entity.width; // entity2.height = 2; this.entity.width--; this.body = box2d.createRectangle(entity, definition); // this.placeholderBody = box2d.createRectangle(entity2, definition); this.sensorsDef = [ {x: 0, y: -entity.height/2/box2d.scale, width: entity.width, height: 3, name:"top"} ]; this.sensors = box2d.addSensors(this.body, this.sensorsDef); this.body.SetFixedRotation(true); this.body.SetUserData(this); // this.placeholderBody.SetUserData(this); } wallBrick.prototype.update = function () { this.updatePosition(); if(this.state === "tap"){ this.checkTapping(); } }; wallBrick.prototype.updatePosition = function () { // if(this.body.GetType() === Box2D.Dynamics.b2Body.b2_staticBody) return; if(!this.body.IsAwake()){ this.body.SetType(Box2D.Dynamics.b2Body.b2_staticBody); return; } var position = this.body.GetPosition(); var angle = this.body.GetAngle(); this.sprite.position.x = (position.x * box2d.scale); this.sprite.position.y = position.y * box2d.scale; this.sprite.rotation = angle; }; wallBrick.prototype.tap = function () { if(this.state === "tap") return; this.body.SetType(Box2D.Dynamics.b2Body.b2_dynamicBody); this.state = "tap"; var vec = new Box2D.Common.Math.b2Vec2(0, -this.definition.verticalImpulse); this.body.ApplyImpulse(vec, this.body.GetWorldCenter()); this.Contacts.top.forEach(function(e, i, a){ var character = e.GetBody().GetUserData(); if(character.type === "enemy" && !(character.pushed || character.died)){ //character.die2(); a.splice(i, 1); } }); }; wallBrick.prototype.checkTapping = function () { var currentPos = this.body.GetPosition(); var currentY = currentPos.y * box2d.scale; if(currentY >= this.entity.y+this.entity.height/2){ this.state = "silent"; currentPos.y = (this.entity.y + this.entity.height/2)/box2d.scale; currentPos.x = (this.entity.x + this.entity.width/2)/box2d.scale; this.body.SetPosition(currentPos); var ve = this.body.GetLinearVelocity(); ve.x = ve.y = 0.0; this.body.SetLinearVelocity(ve); this.body.SetType(Box2D.Dynamics.b2Body.b2_staticBody); }else { currentPos.x = (this.entity.x + this.entity.width/2)/box2d.scale; this.body.SetPosition(currentPos); } };/*global angular, Session */ 'use strict'; var angularMeteorSession = angular.module('angular-meteor.session', ['angular-meteor.utils']); angularMeteorSession.factory('$meteorSession', ['$meteorUtils', '$parse', '$angularMeteorSettings', function ($meteorUtils, $parse, $angularMeteorSettings) { return function (session) { return { bind: function(scope, model) { if (!$angularMeteorSettings.suppressWarnings) console.warn('[angular-meteor.session.bind] Please note that this method is deprecated since 1.3.0 and will be removed in 1.4.0! http://www.angular-meteor.com/api/1.3.0/session. You can disable this warning by following this guide http://www.angular-meteor.com/api/1.3.6/settings'); var getter = $parse(model); var setter = getter.assign; $meteorUtils.autorun(scope, function() { setter(scope, Session.get(session)); }); scope.$watch(model, function(newItem, oldItem) { Session.set(session, getter(scope)); }, true); } }; }; } ]); const Web3 = require("web3"); const net = require("net"); const IPCProvider = path => { return new Web3(path, net); }; const WSProvider = path => { return new Web3(path); }; const HTTPProvider = path => { return new Web3(path); }; /** * * @param {String} chain the chain, e.g "mainnet" * @param {Object} spec see example below * @returns {Provider} a Web3 provider * * @example * { * type: "WS_Infura", * envKeyID: "PROVIDER_INFURA_ID" * } */ const ProviderFor = (chain, spec) => { switch (spec.type) { case "IPC": return IPCProvider(process.env[spec.envKeyPath]); case "WS_Infura": return WSProvider( `wss://${chain}.infura.io/ws/v3/` + process.env[spec.envKeyID] ); case "WS_Alchemy": return WSProvider( `wss://eth-${chain}.ws.alchemyapi.io/v2/` + process.env[spec.envKeyKey] ); case "HTTP_Infura": return HTTPProvider( `https://${chain}.infura.io/v3/` + process.env[spec.envKeyID] ); case "HTTP_Alchemy": return HTTPProvider( `https://eth-${chain}.alchemyapi.io/v2/` + process.env[spec.envKeyKey] ); case "HTTP_OEC": return HTTPProvider( `https://exchainrpc.okex.org` ); case "WS_OEC": return HTTPProvider( `wss://exchainws.okex.org:8443` ); } }; exports.ProviderFor = ProviderFor; /** * * @param {String} chain the chain, e.g "mainnet" * @param {Object} specs see example below * @returns {Array} a Web3 provider * * @example * [ * { * type: "WS_Infura", * envKeyID: "PROVIDER_INFURA_ID" * }, * { * type: "WS_Alchemy", * envKeyKey: "PROVIDER_ALCHEMY_KEY" * } * ] */ const ProvidersFor = (chain, specs) => { return specs.map(spec => ProviderFor(chain, spec)); }; class MultiSendProvider { constructor(chain, specs) { this.providers = ProvidersFor(chain, specs); // Use proxy to match ordinary Web3 API return new Proxy(this, { get: function(target, prop, receiver) { if (prop === "eth") return receiver; if (prop in target) return target[prop]; // fallback return target.providers[0].eth[prop]; } }); } call(tx, block) { return this.providers[0].eth.call(tx, block); } sendSignedTransaction(signedTx) { const sentTx = this.providers[0].eth.sendSignedTransaction(signedTx); for (let i = 1; i < this.providers.length; i++) this.providers[i].eth .sendSignedTransaction(signedTx) .on("error", e => console.log(e.name + " " + e.message)); return sentTx; } clearSubscriptions() { this.providers.forEach(p => p.eth.clearSubscriptions()); } // Double-underscore because this isn't part of the web3.eth namespace __close() { this.providers.forEach(p => { try { p.currentProvider.connection.close(); } catch { try { p.currentProvider.connection.destroy(); } catch { console.log("Cannot close HTTP provider's connection"); } } }); } get currentProvider() { return { connection: { close: this.__close.bind(this) } }; } } exports.MultiSendProvider = MultiSendProvider; amandathedev/ceic_wordpress (function() { window.mc4wp = window.mc4wp || { listeners: [], forms: { on: function(evt, cb) { window.mc4wp.listeners.push( { event : evt, callback: cb } ); } } } })(); 0 /** * User enters some text * Program processes the text such that it can show a list of character * and how many times they were used int the input response string */ const io = require("../modules/io/index") let charcount = {} io.terminal.setPrompt("Enter a string to analyze: ") io.terminal.prompt() io.terminal.on("line", function (response) { let input = response let characters = input.split('') for (let character of characters){ if (charcount[character]){ charcount[character] ++ } else { charcount[character] = 1 } } io.terminal.close() }) .on("close",function(){ let charArr = [] for (let character in charcount ){ io.print (`${character} ${charcount[character]}`) charArr.push({char:character,count:charcount[character]}) } charArr.sort(function(a,b){ if (a.countb.count) return 1 else return 0 }) // console.log("charArr", charArr) io.print("Character count in ascending order:") for (let row of charArr){ io.print (`${row.char} ${row.count}`) } })100-1000 /** * This script will be run once all questions have finished and no errors have * occured. You can congratulate the user on their fine choice in software usage * */ console.log(''); console.log('Config generated! You may now start the server normally.'); console.log(''); /* * * SetNewPasswordPage * */ import React from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { createStructuredSelector } from 'reselect'; import SetNewPasswordForm from '../../components/SetNewPasswordForm'; import { setNewPasswordRequest } from './actions'; export class SetNewPasswordPage extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { onSubmitForm: React.PropTypes.func, }; constructor(props) { super(props); this.onSubmitForm = this.props.onSubmitForm.bind(this); } render() { return (

Enter New Password


); } } const mapStateToProps = createStructuredSelector({ }); function mapDispatchToProps(dispatch) { return { onSubmitForm: (values) => dispatch(setNewPasswordRequest(values)), }; } export default connect(mapStateToProps, mapDispatchToProps)(SetNewPasswordPage); sbeltran10/moncrud const dataManager = require('./data-manager') const authentication = require('../services/authentication') const userManager = { addNew: userData => new Promise((resolve, reject) => { if (!userManager.userExists(userData.username.toLowerCase())) { authentication.encryptPassword(userData.password) .then(encryptedPassword => { dataManager.save({ key: userData.username.toLowerCase(), value: { password: , role: userData.role } }, dataManager.USER_STORE) resolve(userData.password) }) .catch(err => { console.log(err) reject(err) }) } else { reject(new Error('Username already exists')) } }), userExists: (username) => { return dataManager.read(dataManager.USER_STORE)[username] }, loadUsers: () => { const usersObj = dataManager.read(dataManager.USER_STORE) let userList = [] Object.keys(usersObj).forEach(key => { userList.push({ username: key, role: usersObj[key].role }) }) return userList } } module.exports = userManager JetBrains/youtrack-mobile /* @flow */ import EStyleSheet from 'react-native-extended-stylesheet'; import {UNIT} from '../variables/variables'; import {issueCard, issueIdResolved} from '../common-styles/issue'; import {secondaryText} from '../common-styles/typography'; export const agileCard = { flexDirection: 'row', marginLeft: UNIT * 2, borderRadius: UNIT, overflow: 'hidden', backgroundColor: '$boxBackground', }; export default (EStyleSheet.create({ card: agileCard, cardColorCoding: { flexShrink: 0, marginTop: UNIT / 4, marginBottom: UNIT / 4, width: UNIT / 2, borderTopLeftRadius: UNIT, borderBottomLeftRadius: UNIT, }, cardContainer: { flexGrow: 1, flexDirection: 'column', padding: UNIT * 1.75, paddingTop: UNIT * 1.5, }, cardContainerNotZoomed: { padding: UNIT, paddingTop: UNIT, }, cardContent: { flexDirection: 'column', }, issueHeader: { flexDirection: 'row', }, issueHeaderLeft: { flexGrow: 1, }, issueContent: { flexGrow: 1, flexDirection: 'column', justifyContent: 'space-between', }, issueSummary: { flexGrow: 1, color: '$text', }, ghost: { display: 'none', }, dragging: { width: '80%', transform: [{rotate: '-3deg'}], borderWidth: 2, borderColor: '$iconAccent', }, draggingZoomedOut: { width: '38%' }, estimation: { marginRight: UNIT, ...secondaryText, color: '$icon', }, summary: { flexGrow: 1, ...issueCard.issueSummary, marginTop: UNIT, }, issueId: { ...issueCard.issueId, color: '$icon', }, issueIdResolved: { ...issueIdResolved, }, assignees: { flexDirection: 'row', alignItems: 'center', }, assignee: { marginLeft: UNIT / 2, }, tags: { flexGrow: 0, overflow: 'hidden', height: UNIT * 3.5, marginTop: UNIT / 2, }, zoomedInText: { fontSize: 11, }, }): any); module.exports = require('./dist/tl') 1-10 'use strict'; /** * Report invalid use of the utility. * * @param {String} msg Erorr message * @returns {Exception} */ export default function invalidUse(msg) { throw new Error(`Powercheck: ${msg}`); }; rapid.WxSdk = (function () { let wxSdk, jsApiListConfig = ["checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo", "updateAppMessageShareData", "updateTimelineShareData", "hideMenuItems", "showMenuItems", "hideAllNonBaseMenuItem", "showAllNonBaseMenuItem", "translateVoice", "startRecord", "stopRecord", "onRecordEnd", "playVoice", "pauseVoice", "stopVoice", "uploadVoice", "downloadVoice", "chooseImage", "previewImage", "uploadImage", "downloadImage", "getNetworkType", "openLocation", "getLocation", "hideOptionMenu", "showOptionMenu", "closeWindow", "scanQRCode", "chooseWXPay", "openProductSpecificView", "addCard", "chooseCard", "openCard"]; /** * WxSdk初始化 * @param debug * @param callback * @param jsApiList * @constructor */ function WxSdk(debug, callback, jsApiList) { wxSdk = this; this.setDebug(debug); this.setApiList(jsApiList); this.wxSdkConfig = rapid.getJavaScriptContentConfig(rapid.getGlobalConfig().dataNames.contentConfigWxSdk).toObject(); this.setWxAppId(rapid.getBuild().getData(this.wxSdkConfig, 'appId')); this.setTimestamp(rapid.getBuild().getData(this.wxSdkConfig, 'timestamp')); this.setNonceStr(rapid.getBuild().getData(this.wxSdkConfig, 'nonceStr')); this.setSignature(rapid.getBuild().getData(this.wxSdkConfig, 'signature')); this.setSignature(rapid.getBuild().getData(this.wxSdkConfig, 'signature')); typeof callback === 'function' ? callback(this.wxSdkConfig) : null; this.setWxObject().setWxConfig(this.getWxSdkConfig()); } /** * 获取wxSdkConfig * @returns {{debug, appId, timestamp, nonceStr, signature, jsApiList}} */ WxSdk.prototype.getWxSdkConfig = function () { return { debug: this.getDebug(), appId: this.getWxAppId(), timestamp: this.getTimestamp(), nonceStr: this.getNonceStr(), signature: this.getSignature(), jsApiList: this.getApiList() }; }; /** * 设置wx对象 * @returns {WxSdk} */ WxSdk.prototype.setWxObject = function () { this.jweixin = typeof wx != 'object' ? function () { throw new Error('Please first introduce jweixin.js'); }() : wx; return this; }; /** * 设置wxConfig * @param config * @returns {WxSdk} */ WxSdk.prototype.setWxConfig = function (config) { this.jweixin.config(config); return this; }; /** * 设置debug * @param debug * @returns {WxSdk} */ WxSdk.prototype.setDebug = function (debug) { this.debug = debug || false; return this; }; /** * 获取debug * @returns {*|boolean} */ WxSdk.prototype.getDebug = function () { return this.debug; }; /** * 设置wxAppId * @param appId * @returns {WxSdk} */ WxSdk.prototype.setWxAppId = function (appId) { this.appId = appId || null; return this; }; /** * 获取wxAppId * @returns {*|null} */ WxSdk.prototype.getWxAppId = function () { return this.appId; }; /** * 设置timestamp * @param timestamp * @returns {WxSdk} */ WxSdk.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp || null; return this; }; /** * 获取timestamp * @returns {*|null} */ WxSdk.prototype.getTimestamp = function () { return this.timestamp; }; /** * 设置NonceStr * @param nonceStr * @returns {WxSdk} */ WxSdk.prototype.setNonceStr = function (nonceStr) { this.nonceStr = nonceStr || null; return this; }; /** * 获取NonceStr * @returns {*|null} */ WxSdk.prototype.getNonceStr = function () { return this.nonceStr; }; /** * 设置Signature * @param signature * @returns {WxSdk} */ WxSdk.prototype.setSignature = function (signature) { this.signature = signature || null; return this; }; /** * 获取Signature * @returns {*|null} */ WxSdk.prototype.getSignature = function () { return this.signature; }; /** * 设置ApiList * @param list * @returns {WxSdk} */ WxSdk.prototype.setApiList = function (list) { this.jsApiList = list instanceof Array ? function () { const apiList = []; for (let i in list) if (jsApiListConfig.indexOf(list[i]) >= 0) apiList.push(list[i]); return apiList; }() : jsApiListConfig; return this; }; /** * 获取ApiList * @returns {string[]|*} */ WxSdk.prototype.getApiList = function () { return this.jsApiList; }; /** * 设置WxSdk对象参数 * @param name * @param value * @returns {WxSdk} */ WxSdk.prototype.setWxSdk = function (name, value) { const callback = this.jweixin[name]; typeof callback === 'function' ? this.jweixin[name](value) : null; return this; }; /** * 设置分享到朋友圈 * @param title * @param link * @param icon * @param success * @returns {WxSdk} */ WxSdk.prototype.setWxShareTimeline = function (title, link, icon, success) { const value = {title: title, link: link, imgUrl: icon, success: success}; return this.setWxSdk('updateTimelineShareData', value); }; /** * 设置分享给朋友 * @param title * @param desc * @param link * @param icon * @param success * @returns {WxSdk} */ WxSdk.prototype.setWxShareAppMessage = function (title, desc, link, icon, success) { const value = { title: title, desc: desc, link: link, imgUrl: icon, success: success }; return this.setWxSdk('updateAppMessageShareData', value); }; /** * 选择图片 * @param call * @param param * @param uploadComplete * @returns {WxSdk} */ WxSdk.prototype.chooseImage = function (call, param, uploadComplete) { const _param = rapid.getBuild().extend({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], }, param); _param.success = function (res) { const localIds = res.localIds; rapid.getBuild().callback(call, localIds, res); if (typeof uploadComplete === "function") return wxSdk.uploadImage(localIds.toString(), uploadComplete, 1); }; return this.setWxSdk('chooseImage', _param); }; /** * 上传图片 * @param localId 需要上传的图片的本地ID,由chooseImage接口获得 * @param call * @param isShowProgressTips 默认为1,显示进度提示 * @returns {WxSdk} */ WxSdk.prototype.uploadImage = function (localId, call, isShowProgressTips) { isShowProgressTips = isShowProgressTips || 1; return this.setWxSdk('uploadImage', { localId: localId, isShowProgressTips: isShowProgressTips, complete: function (res) { rapid.getBuild().callback(call, res.serverId, res); } }); }; /** * 获取本地图片base64数据 * @param localId * @param call * @returns {WxSdk} */ WxSdk.prototype.getLocalImgData = function (localId, call) { return this.setWxSdk("getLocalImgData", { localId: localId, success: function (res) { rapid.getBuild().callback(call, res.localData, res); } }); }; /** * 包装微信录音程序 * @type {RecordModule} */ const RecordModule = (function () { let time = 0; let timer = 0; let recordModule = null; /** * 初始化 * @constructor * @param param */ function RecordModule(param) { recordModule = this; this.param = rapid.getBuild().extend(this.param, param); } /** * 参数 * @type {{uploadComplete: null, maxTime: number, minTime: number, start: null, complete: null, isAutoUp: boolean}} */ RecordModule.prototype.param = { /** * 录音最小时间 */ minTime: 5, /** * 录音最大时间 */ maxTime: 60, /** * 录音开始回调函数 */ start: null, /** * 录音完毕回调函数 */ complete: null, /** * 上传完成回调 */ uploadComplete: null, /** * 是否自动上传 */ isAutoUp: false, }; /** * 语音文件Id * @type {string} */ RecordModule.prototype.localId = ''; /** * 开始录音 */ RecordModule.prototype.start = function () { time = 0; this.localId = ''; this.runInterval(); wxSdk.startRecord(function (res) { rapid.getBuild().callback(recordModule.param.start, res); }.bind(this)); }; /** * 停止录音 * @param res 自动停止接口过来的 * @returns {boolean} */ RecordModule.prototype.stop = function (res) { function completeCall(res) { clearInterval(timer); recordModule.localId = res.localId; rapid.getBuild().callback(recordModule.param.complete, recordModule.localId, time, res); if (time < recordModule.param.minTime) return false; if (recordModule.param.isAutoUp === true) recordModule.uploadVoice(); } if (typeof res === 'object' && res !== null) return completeCall(res); wxSdk.stopRecord(completeCall); }; /** * 上传语音 */ RecordModule.prototype.uploadVoice = function () { if (!this.localId) throw new Error('localId is empty!'); wxSdk.uploadVoice(this.localId, function (res) { clearInterval(timer); rapid.getBuild().callback(recordModule.param.uploadComplete, res.serverId, time, res); }.bind(this)); }; /** * 计时 */ RecordModule.prototype.runInterval = function () { wxSdk.setWxSdk('onVoiceRecordEnd', { complete: function (res) { recordModule.stop(res) || clearInterval(timer); } }); timer = setInterval(function () { if (time >= this.param.maxTime) this.stop() || clearInterval(timer); time++; }.bind(this), 1000); }; return RecordModule; })(); /** * 开始录音 * @param call */ WxSdk.prototype.startRecord = function (call) { return this.setWxSdk('startRecord', {complete: call}); }; /** * 停止录音 * @param call * @returns {WxSdk} */ WxSdk.prototype.stopRecord = function (call) { return this.setWxSdk('stopRecord', {success: call}); }; /** * 上传语音 * @param localId * @param call * @returns {WxSdk} */ WxSdk.prototype.uploadVoice = function (localId, call) { return this.setWxSdk('uploadVoice', {localId: localId, success: call}); }; /** * 播放本地录音接口 * @param localId * @returns {WxSdk} */ WxSdk.prototype.playVoice = function (localId) { return this.setWxSdk('playVoice', {localId: localId}); }; /** * 暂停播放本地录音接口 * @param localId * @returns {WxSdk} */ WxSdk.prototype.pauseVoice = function (localId) { return this.setWxSdk('pauseVoice', {localId: localId}); }; /** * 监听录音播放完毕 * @param call * @returns {WxSdk} */ WxSdk.prototype.onVoicePlayEnd = function (call) { return this.setWxSdk('onVoicePlayEnd', {success: call}); }; /** * 停止播放本地录音接口 * @param localId * @returns {WxSdk} */ WxSdk.prototype.stopVoice = function (localId) { return this.setWxSdk('stopVoice', {localId: localId}); }; /** * 下载语音接口 * @returns {WxSdk} * @param serverId * @param isShow * @param call */ WxSdk.prototype.downloadVoice = function (serverId, isShow, call) { return this.setWxSdk('downloadVoice', {serverId: serverId, isShowProgressTips: isShow, success: call}); }; /** * 识别音频并返回识别结果接口 * @returns {WxSdk} * @param localId * @param isShow * @param call */ WxSdk.prototype.translateVoice = function (localId, isShow, call) { return this.setWxSdk('downloadVoice', {localId: localId, isShowProgressTips: isShow, success: call}); }; /** * 获取微信录音集成程序 * @returns {RecordModule} * @param param */ WxSdk.prototype.getRecordModule = function (param) { return new RecordModule(param); }; /** * 长按录音 * @param recordModule * @param view * @param uploadComplete * @returns {WxSdk} */ WxSdk.prototype.longTouchRecord = function (recordModule, view, uploadComplete) { if (typeof uploadComplete === 'function') recordModule.param.uploadComplete = uploadComplete; view.once('touchstart', function (e) { e.preventDefault(); recordModule.start(); }.bind(this)); view.once('touchend', function () { recordModule.stop(); }.bind(this)); return this; }; /** * 载入完毕回调事件 * @param callback * @returns {WxSdk} */ WxSdk.prototype.ready = function (callback) { this.jweixin.ready(function () { typeof callback === 'function' ? callback(wxSdk) : null; }); return this; }; return WxSdk; })();client/src/context/Errors/ErrorReducer.js const ErrorReducer = (state, action) => { if (action.type === "GET_ERRORS") { return { message: action.payload.message, status: action.payload.status, id: action.payload.id, }; } else if (action.type === "CLEAR_ERRORS") { return { message: {}, status: null, id: null, }; } else { return state; } }; export default ErrorReducer; 'use strict'; const config = {}; /** * Discord API/bot settings * * @type {Object} */ config.discord = { /** * The user IDs that should be considered admins. * * @type {Array} */ admins: [ '81332863928119296', '66271559538446336', '99787077444464640', '89332412911210496', '140911637321351168', '99618921019117568', '141813591459364864', '99655085218336768', '135050210899394560', '203343129338839040', ], /** * The Discord client ID for authentication with the web interface. * * @type {String} */ clientId: '', /** * The Discord client secret for authentication. * * @type {String} */ clientSecret: '', /** * The Discord authentication redirect URI. * * @type {String} */ redirectUri: 'http://localhost:8000/auth/discord/callback', /** * Should the bot show as offline in the userlist? * * @type {Boolean} */ showAsOffline: false, /** * The Discord bot token * * @type {String} */ token: '', }; /** * See Google Cloud options: https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/latest/google-cloud * * @type {Object} */ config.gcloud = { projectId: 'grape-spaceship-123', keyFilename: '/path/to/key.json', }; /** * Miscellaneous settings used by the bot. * * @type {Object} */ config.settings = { /** * The prefix for admin commands. * * @type {String} */ cmdPrefix: '!', /** * Location of data file with information about what is ignored (channels, users etc.) * * @type {String} */ ignore: __dirname + '/data/ignore.json', /** * Location of settings file for extra settings * * @type {String} */ settings: __dirname + '/data/settings.json', /** * Guilds and channels that are "forbidden" to request messages for. * These guild IDs and channel IDs will not show up in the /api/channels endpoint * and thus not in the web UI as well. * * ** Keep in mind that messages from these channels and guilds will still be logged. * ** Therefore making it different from the ignore.json file. */ forbidden: { channels: [], guilds: [], }, /** * API tokens that do not require any other authentication. */ apiTokens: [], /** * Express-related settings. * * @type {Object} */ express: { /** * If the Express web server is enabled or not. * * @type {Boolean} */ enabled: false, /** * The port Express should listen to. * * @type {Number} */ port: process.env.PORT || 8000, /** * The maximum amount of messages allowed to request through the Express API. * * @type {Number} */ maxLimit: 50, /** * Website title * * @type {String} */ title: 'Illuminati Bot', }, /** * The different "kinds" for the different types of information to store. * * @type {Object} */ gcloud: { logs: 'logs', messages: 'messages', }, }; module.exports = config; const chai = require('chai'); chai.config.truncateThreshold = 0; chai.config.includeStack = true; chai.use(require('chai-subset')); chai.use(require('sinon-chai')); require('babel-polyfill'); var contextualRequire = require.context('./src', true, /\.test\.js$/); contextualRequire.keys().forEach(contextualRequire); import sum from '../sum.js'; import chai from "chai" describe('Test Sum', function () { it('should return sum of arguments 1', function () { chai.expect(sum(1, 2)).to.equal(3); }); it('should return sum of arguments 2', function () { chai.expect(sum(2, 3)).to.equal(5); }); }); const path = require('path'); const fs = require('fs-extra'); const projectPath = process.cwd(); const utils = require('../utils'); const initPath = path.resolve(__dirname, '../init'); const docsPath = path.resolve(projectPath, 'docs'); const projectConfig = path.resolve(projectPath, 'ydoc.json'); const initydoc = require('../initydoc'); module.exports = { setOptions: function () {}, run: function () { let configFilepath = utils.getConfigPath(projectPath); if (configFilepath) { return utils.log.error('The current directory already exists ydoc config.') }else if (utils.dirExist(docsPath)) { return utils.log.error('The current directory already exists directory "docs".'); } const configs = initydoc(); if(Object.keys(configs).length > 0){ fs.writeFileSync(projectConfig, JSON.stringify(configs, {}, 2)); } fs.ensureDirSync(docsPath); fs.copySync(initPath, docsPath); utils.log.ok('Initialization successful, please use the following command to generate the documents site.') utils.log.info('Execute: "ydoc build"') }, desc: 'Initialize a document site' }0 /** * Created by matheusbmleite on 09/02/17. */ //use jQuery for a Delete confirmation pop-up $('.confirmation').on('click', function() { return confirm('Are you sure you want to delete this item?'); })0 const Glue = require('glue'); const env = process.env; let portNumber; let hostUrl; let connectionString; let collectionName; if (env.NODE_PORT === undefined && env.docker === undefined) { portNumber = 9000; hostUrl = 'localhost'; connectionString = '127.0.0.1:27017'; collectionName = 'cache'; } else if (env.docker !== undefined) { portNumber = 9000; hostUrl = '0.0.0.0'; connectionString = 'db:27017'; } else { portNumber = env.NODE_PORT; hostUrl = env.NODE_IP; collectionName = env.OPENSHIFT_APP_NAME; /*eslint-disable */ connectionString = env.OPENSHIFT_MONGODB_DB_USERNAME + ':' + env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' + env.OPENSHIFT_MONGODB_DB_HOST + ':' + env.OPENSHIFT_MONGODB_DB_PORT + '/' + env.OPENSHIFT_APP_NAME; /*eslint-enable */ } const manifest = { server: { cache: [{ engine: 'catbox-mongodb', uri: `mongodb://${connectionString}`, partition: collectionName, name: 'mongo', }], }, connections: [{ host: hostUrl, port: portNumber, labels: ['api'], routes: { cors: true, }, }], registrations: [{ plugin: { register: 'inert', }, options: { select: 'api', }, }, { plugin: { register: 'vision', }, options: { select: 'api', }, }, { plugin: { register: 'hapi-swagger', options: { jsonPath: '/documentation/swagger.json', schemes: ['https'], info: { title: 'Unofficial Overwatch API', version: '1.0', }, }, }, options: { select: 'api', }, }, { plugin: { register: 'hapi-rate-limit', // https://github.com/wraithgar/hapi-rate-limit options: { userCache: { expiresIn: 60000, }, }, }, options: { select: 'api', }, }, { plugin: { register: './routes/patch_notes.js', }, options: { select: 'api', }, }, { plugin: { register: './routes/achievements.js', }, options: { select: 'api', }, }, { plugin: { register: './routes/allHeroes.js', }, options: { select: 'api', }, }, { plugin: { register: './routes/heroes.js', }, options: { select: 'api', }, }, { plugin: { register: './routes/hero.js', }, options: { select: 'api', }, }, { plugin: { register: './routes/profile.js', }, options: { select: 'api', }, }, { plugin: { register: './routes/get-platforms.js', }, options: { select: 'api', }, }, ], }; const options = { relativeTo: __dirname, }; Glue.compose(manifest, options, (err, server) => { if (err) { throw err; } server.route({ method: 'GET', path: '/favicon.ico', handler: { file: 'favicon.ico' }, config: { cache: { expiresIn: 86400000 } } }); if (!module.parent) { server.start(() => { console.log('\x1b[36m', '╔══════════════════════════════════════════╗', '\x1b[0m'); console.log('\x1b[36m', '║ LootBox Api - An unoffical Overwatch Api ║', '\x1b[0m'); console.log('\x1b[36m', '║══════════════════════════════════════════║', '\x1b[0m'); console.log('\x1b[36m', `║ URL: ${server.info.uri} ║`, '\x1b[0m'); console.log('\x1b[36m', '║ ║', '\x1b[0m'); console.log('\x1b[36m', '╚══════════════════════════════════════════╝', '\x1b[0m'); }); } else { module.exports = server; } }); export default object => { const foo = Object.entries(object).reduce((accumulator, [key, value]) => { if (accumulator) { accumulator += ';' } return `${accumulator}${key}=${value || ''}` }, '').replace(/\s/gu, '\\s') return foo } ( function() { var ns = window.b$l; var $$ = ns.$$; var sn = ns.sn; var rootvm = sn('rootvm'); var cssp = ns.CSS_PREFIX; var sapp = sn('sapp' ); var fapp = ns.sn('fapp' ); var fconf = ns.sn('fconf',fapp); var sconf = ns.sn('sconf',fconf); var sDomN = sn('dnative', sapp); var sDomF = sn('dfunctions', sapp); var studyMods = sn('studyMods', sapp); var amode = sn('mode',sapp); var ss = sn('ss', fapp); var ssF = sn('ssFunctions',ss); ssF.mod2inn = mod2inn; ssF.mod2inn_original = mod2inn_original; sDomF.out2inn = out2inn; sDomF.outparent2inn = outparent2inn; sDomF.inn2outparent = inn2outparent; return; //========================================== // //\\ pos to pos //========================================== ///transforms model-coordinates to media-coordinates function mod2inn( pos ) { if( !pos ) { pos = this; } return [ pos[0] * sconf.mod2inn_scale + sconf.activeAreaOffsetX, pos[1] * sconf.mod2inn_scale * sconf.MONITOR_Y_FLIP + sconf.activeAreaOffsetY, ]; } ///purpose: use for controls undependent on model scale and origin /// user controls, function mod2inn_original( pos ) { if( !pos ) { pos = this; } return [ pos[0] * sconf.originalMod2inn_scale + //sconf.activeAreaOffsetX, sconf.originX_onPicture, pos[1] * sconf.originalMod2inn_scale * sconf.MONITOR_Y_FLIP + //sconf.activeAreaOffsetY, sconf.originY_onPicture, ]; } //========================================== // \\// pos to pos //========================================== //=============================== // //\\ inn2outparent and inverse //=============================== ///wrong?: converts pos-in-media-scope to pos-in-dom-scope-related-to-media-dom-offset ///right? .... to-media-parent-dom-offset function inn2outparent() { var off = sconf.mediaOffset; var medpos = this.medpos; var i2o = 1/sDomF.out2inn(); return [ medpos[0] * i2o + off[0], //this is not required because of media root already margined, so //has been shifted as mediaLeftMargin // + sDomN.mediaLeftMargin, medpos[1] * i2o + off[1] ]; }; ///converts dom-pos to media pos ///for lemma1, drag_surface = sDomN.medRoot function outparent2inn( outparent ) { var moffset = sconf.mediaOffset; var c2m = sDomF.out2inn(); return [ c2m * ( outparent[0] - moffset[0] //- sDomN.mediaLeftMargin //media-root is already shifted ... ), c2m * ( outparent[1] - moffset[1] ) ]; }; //=============================== // \\// inn2outparent and inverse //=============================== function out2inn() { return sconf.innerMediaWidth / sDomN.mediaWidth; /* //todm: for this at the moment, have to define amode['submodel'] even // at phase content2exegs.js ... too early ... var sm = studyMods[ amode['submodel'] ]; var me = sm.mmedia; var re = me.getBoundingClientRect(); var wi = re.width; if( wi === 0 ) { wi = sconf.innerMediaWidth; //ccc( '**** alert: width === 0: media=', me, 'rect=', re ); //ccc( '**** alert: width === 0:'); } else { //ccc( '**** scale is set to = ' + sconf.innerMediaWidth / wi ); } return sconf.innerMediaWidth / wi; //studyMods[ amode['submodel'] ].mmedia.getBoundingClientRect().width; */ }; }) (); // pages/express/express_detail/express_detail.js var utils = require('../../../utils/util.js'); var app = getApp(); Page({ /** * 页面的初始数据 */ data: { express_detail_id: "", express: {}, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.data.express_detail_id = options.express_detail_id; this.getExpressByDetailId(); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, express_accept: function () { var that = this; var phone = wx.getStorageSync('phone'); if (phone === that.data.express.publish_id) { wx.showModal({ content: "自己不能接自己发布订单", showCancel: false, confirmText: "确定", }) } else { wx.request({ url: app.globalData.url + '/express/accept', data: { express_detail_id: that.data.express_detail_id, accept_id: phone }, header: { "Content-Type": "application/x-www-form-urlencoded" }, method: 'POST', success: function (res) { if (res.data.code == 200) { wx.showModal({ content: res.data.message, showCancel: false, confirmText: "确定", success(res) { if (res.confirm) { wx.switchTab({ url: '/pages/order/order', }) } } }) } else { console.log("获取失败") } } }) } }, getExpressByDetailId: function () { var that = this wx.request({ url: app.globalData.url + '/express/detail', data: { express_detail_id: this.data.express_detail_id }, header: { "Content-Type": "application/x-www-form-urlencoded" }, method: 'GET', success: function (res) { if (res.data.code == 200) { var date = res.data.data.expressDetail.express_publishtime; if (date != null) { date = utils.formatTime(new Date(date)) res.data.data.expressDetail.express_publishtime = date; } that.setData({ express: res.data.data }); } else { console.log("获取失败") } } }) } })import Listener from "./Listener" import Logger from "./Logger" import Indexer from "./Indexer" import { replaceInKeys } from "./utilities" export default class Pipeline { constructor() { this.listener = new Listener() this.logger = new Logger() this.indexer = new Indexer() } /** * Runs the pipeline */ async run() { await this.listener.listen(async (message) => { this.logger.debug(`received message: ${JSON.stringify(message)}`) if (!["insert", "replace", "delete"].includes(message.operationType)) return // Need to map ! back to . in keys. const doc = replaceInKeys(message.fullDocument, "!", ".") // Invoke the method for the operation type this[message.operationType](doc) }) } insert(doc) { this.indexer.index(doc) } // Updates and creates are handled the same way since we index w/ an ID replace(doc) { this.insert(doc) } delete(doc) { this.indexer.delete(doc) } } ManatiCR/generator-manati-themetest/test-app.js 'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('manati theme:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../generators/app')) .withOptions({ skipInstall: true }) .withPrompts({ themeName: 'Manatí Theme' }) .on('end', done); }); it('creates files', function () { assert.file([ 'package.json', '.editorconfig', '.jshintrc', '.gitignore', 'Gruntfile.js', 'template.php', 'theme-settings.php', 'manati_theme.info', 'src-js', 'sass', 'css', 'templates', 'templates/system/html.tpl.php', 'templates/system/page.tpl.php' ]); }); }); assets/js/pages/input_text.js // Input Text // © Codrops (function(window) { 'use strict'; // class helper functions from bonzo https://github.com/ded/bonzo function classReg(className) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } var hasClass, addClass, removeClass; if ('classList' in document.documentElement) { hasClass = function(elem, c) { return elem.classList.contains(c); }; addClass = function(elem, c) { elem.classList.add(c); }; removeClass = function(elem, c) { elem.classList.remove(c); }; } else { hasClass = function(elem, c) { return classReg(c).test(elem.className); }; addClass = function(elem, c) { if (!hasClass(elem, c)) { elem.className = elem.className + ' ' + c; } }; removeClass = function(elem, c) { elem.className = elem.className.replace(classReg(c), ' '); }; } function toggleClass(elem, c) { var fn = hasClass(elem, c) ? removeClass : addClass; fn(elem, c); } var classie = { hasClass: hasClass, addClass: addClass, removeClass: removeClass, toggleClass: toggleClass, has: hasClass, add: addClass, remove: removeClass, toggle: toggleClass }; if (typeof define === 'function' && define.amd) define(classie); else window.classie = classie; if (!String.prototype.trim) { (function() { var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return this.replace(rtrim, ''); }; })(); } [].slice.call(document.querySelectorAll('input.input__field')).forEach(function(inputEl) { if (inputEl.value.trim() !== '') { classie.add(inputEl.parentNode, 'input--filled'); } inputEl.addEventListener('focus', onInputFocus); inputEl.addEventListener('blur', onInputBlur); }); function onInputFocus(ev) { classie.add(ev.target.parentNode, 'input--filled'); } function onInputBlur(ev) { if (ev.target.value.trim() === '') { classie.remove(ev.target.parentNode, 'input--filled'); } } })(window);scopely/deck 'use strict'; import { PIPELINE_CONFIG_PROVIDER } from 'core/pipeline/config/pipelineConfigProvider'; const angular = require('angular'); module.exports = angular .module('spinnaker.core.pipeline.stage.findImageFromTagsStage', [PIPELINE_CONFIG_PROVIDER]) .config(function(pipelineConfigProvider) { pipelineConfigProvider.registerStage({ useBaseProvider: true, key: 'findImageFromTags', label: 'Find Image from Tags', description: 'Finds an image to deploy from existing tags', }); }); const clear = require('./clear-all'); const load = require('./load'); const defaultConfig = require('../config/impinj-defaults.json'); function setConfig(itemsense, config) { return clear(itemsense) .then( () => load(itemsense, config.configToLoad, config.facility, config.addPassword) ) .then( () => { if (config.completeClear) { return Promise.resolve(); } return load(itemsense, defaultConfig); } ); } module.exports = setConfig; /* * Copyright 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import withRouter from "react-router-dom/es/withRouter"; export default function (ProtectedComponent) { class Authenticate extends React.Component { componentWillMount() { if (!this.props.isAuthenticated) { this.props.history.push('/'); } } componentWillUpdate(props) { if (!props.isAuthenticated) { this.props.history.push('/'); } } render() { return ( ); } } Authenticate.contextTypes = { router: PropTypes.object.isRequired } function mapStateToProps(state) { return { isAuthenticated: state.auth.isAuthenticated }; } return withRouter(connect(mapStateToProps)(Authenticate)); } import React from 'react' import { Title, styles, Section } from "../../utils" import {StaticQuery, graphql} from 'gatsby' const BLOG_POSTS = graphql` { posts:allContentfulBlog{ edges{ node{ id, ueberschrift, artikel{ childContentfulRichText { html } } } } } } ` export default function BlogPost() { return (
{ const posts = data.posts.edges return posts.map(item => { return
{item.node.ueberschrift} {item.node.artikel.childContentfulRichText.html}
}) } }>
) } config.js const dotenv = require('dotenv') dotenv.config(); module.exports = { dbDriver: process.env.DB_DRIVER, dbName: process.env.DB_NAME, dbUser: process.env.DB_USER, dbPassword: process.env.DB_PASSWORD, host: process.env.HOST, port: process.env.PORT } src/actions/countries.js import { GET_COUNTRIES_SUCCESS, GET_COUNTRIES_LOADING, GET_COUNTRIES_ERROR } from 'constants/countries'; import { SET_FILTERS } from 'constants/filters'; import { store } from 'main'; export function getCountries() { return (dispatch) => { // 2019-10-16 client wanted to remove Taiwan in countries list const query = `https://wri-01.carto.com/api/v2/sql?q= SELECT iso as id, name_engli as name, json(bbox) as geometry from gadm28_countries WHERE bbox IS NOT NULL AND iso != 'TWN' ORDER BY name ASC`; // Start loading dispatch({ type: GET_COUNTRIES_LOADING, payload: true }); fetch(new Request(query)) .then((response) => { if (response.ok) return response.json(); throw new Error(response.statusText); }) .then((data) => { dispatch({ type: GET_COUNTRIES_SUCCESS, payload: data.rows }); // End loading dispatch({ type: GET_COUNTRIES_LOADING, payload: false }); // Sets country name const { filters } = store.getState(); const { country } = filters; const countryName = ((data.rows || []).find(c => c.id === country) || {}).name; dispatch({ type: SET_FILTERS, payload: { countryName } }); }) .catch((err) => { // Fetch from server ko -> Dispatch error dispatch({ type: GET_COUNTRIES_ERROR, payload: err.message }); // End loading dispatch({ type: GET_COUNTRIES_LOADING, payload: false }); }); }; } export default getCountries; import Vue from "vue"; export const getMainNav = () => Vue.flamelinkApp.nav.getItems("mainNavigation", { structure: "nested" }); // swap cities between two paths at the index position var swapCityTwoPaths = function(p1, p2, index) { var temp = p1[index]; p1[index] = p2[index]; p2[index] = temp; }; // swap p[i] with p[j] var swapCityOnePath = function(p, i, j) { var temp = p[i]; p[i] = p[j]; p[j] = temp; }; // randomly pick and return two indices i, j from path p (i < j) and i != 0 var pickTwoIndices = function(p) { var i = Math.floor(1 + Math.random() * (p.length - 1)); var j = i; while (i == j) { j = Math.floor(1 + Math.random() * (p.length - 1)); } return i < j ? [i, j] : [j, i]; }; // swap a random pair of cities and return path exports.citySwapMutation = function(p) { var c = p.slice(0); var twoIndices = pickTwoIndices(p); swapCityOnePath(c, twoIndices[0], twoIndices[1]); return c; }; // reverse a random sub-sequence p[i], p[i + 1], p[i + 2] ... with p[i + 2], p[i + 1], p[i] exports.rsm = exports.randomSequenceMutation = function(p) { var c = p.slice(0); var twoIndices = pickTwoIndices(p); // reverse sequence of cities between p[i] and p[j] for (var i = twoIndices[0], j = twoIndices[1]; i < j; ++i, --j) { swapCityOnePath(c, i, j); } return c; }; // partially mapped crossover exports.pmx = exports.partiallyMappedCrossover = exports.partiallyMatchedCrossover = function(p1, p2, cut1, cut2) { var offspring = [p1.slice(0), p2.slice(0)]; var cut1 = cut1 !== undefined ? cut1 : 1 + Math.floor(Math.random() * (p1.length - 1)); // left side of crossover section var cut2 = cut2 !== undefined ? cut2 : cut1 + 1 + Math.floor(Math.random() * (p1.length - cut1)); // right side of crossover section var mapping1 = []; var mapping2 = []; // create a mapping of swapped cities while swapping cities in crossover section for (var i = cut1; i < cut2; ++i) { mapping2[p1[i]] = p2[i]; mapping1[p2[i]] = p1[i]; swapCityTwoPaths(offspring[0], offspring[1], i); } // repair duplicates in offspring using mapping of swapped cities (before crossover section) for (var i = 1; i < cut1; ++i) { while (mapping1[offspring[0][i]] !== undefined) { offspring[0][i] = mapping1[offspring[0][i]]; } while (mapping2[offspring[1][i]] !== undefined) { offspring[1][i] = mapping2[offspring[1][i]]; } } // repair duplicates in offspring using mapping of swapped cities (after crossover section) for (var i = cut2; i < p1.length; ++i) { while (mapping1[offspring[0][i]] !== undefined) { offspring[0][i] = mapping1[offspring[0][i]]; } while (mapping2[offspring[1][i]] !== undefined) { offspring[1][i] = mapping2[offspring[1][i]]; } } return offspring; };0 import * as exc from './errors.js'; export var BaseClass = undefined; export var Module = undefined; export class RubyObject { constructor(type, collect=true) { if (type === undefined) { this.type = BaseClass; } else { this.type = type; } this.included = []; this.extended = []; if (!(this.type instanceof RubyClass || this.type === undefined)) { throw new TypeError("Ruby object type must inherit from JS RubyClass"); } if (this.type === undefined) { this.public_methods = {}; this.private_methods = {}; this.protected_methods = {}; } else { if (this.type instanceof Object) { this.extended = this.type.included; } if (collect) { // TODO: Don't copy the instance methods! this.public_methods = this.type.collect_public_imethods(); this.private_methods = this.type.collect_private_imethods(); this.protected_methods = this.type.collect_protected_imethods(); for (let method in this.public_methods) { if (this.public_methods.hasOwnProperty(method)) { this.public_methods[method].bound_to = this; } } for (let method in this.protected_methods) { if (this.protected_methods.hasOwnProperty(method)) { this.protected_methods[method].bound_to = this; } } for (let method in this.private_methods) { if (this.private_methods.hasOwnProperty(method)) { this.private_methods[method].bound_to = this; } } } else { this.public_methods = {}; this.private_methods = {}; this.protected_methods = {}; } } this.ivars = {}; this.consts = {this: () => { return this; }}; if (this.type === undefined) { this.name = "BasicObject"; } else { /* // wtf why is there a mysterious int with no value appearing??? if (this.type.name === "Integer") debugger; */ this.name = this.type.name; } // TODO: Make this change depending on the current scope this.allow_private_access = true; this.allow_protected_access = true; } _method_wrapper(type, name, ctx) { return (env, ...args) => { let f = type[name]; if (f.bound_to !== undefined) { env.object_stack.push(f.bound_to); } // debugger; let result = f.call(ctx, env, ...args); if (f.bound_to !== undefined) { env.object_stack.pop(); } return result; }; } _module_imethod_wrapper(method, ctx) { return (env, ...args) => { let f = method; env.object_stack.push(ctx); let result = f.call(ctx, env, ...args); env.object_stack.pop(); return result; }; } methods(name, ctx) { if (ctx === undefined) { ctx = this; } // Look up method in this object if (name in this.public_methods) { return this._method_wrapper(this.public_methods, name, ctx); } if ((name in this.protected_methods) && this.allow_protected_access) { return this._method_wrapper(this.protected_methods, name, ctx); } if ((name in this.private_methods) && this.allow_private_access) { return this._method_wrapper(this.private_methods, name, ctx); } // Look up method in extended modules // console.trace(); // console.log(name); // debugger; for (let module of this.extended) { // console.log(module); try { return this._module_imethod_wrapper(module.get_public_imethod(name), ctx); } catch (e) { if (!((e instanceof exc.NoType) || (e instanceof exc.NoMethodError))) { throw e; } } } // console.log("===="); // Look up method in parent object try { let type = this.get_type(); if (type === null) { throw new exc.NoMethodError(`undefined method ${name} for ${this.name}`); } return type.methods(name, ctx); } catch (e) { if (!((e instanceof exc.NoType) || (e instanceof exc.NoMethodError))) { throw e; } } // Lookup failed throw new exc.NoMethodError(`undefined method ${name} for ${this.name}`); } get_type() { if (this.type === this) { throw new exc.NoType(""); } return this.type; } set_type(v) { throw new exc.NoType(""); } get_base() { if (this instanceof RubyClass) { return this.base; } return this.get_type().base; } set_base(v) { if (this instanceof RubyClass) { this.base = v; return; } this.get_type().base = v; } has_method(name) { if (this.public_methods.hasOwnProperty(name)) return true; if (this.private_methods.hasOwnProperty(name)) return true; if (this.protected_methods.hasOwnProperty(name)) return true; return false; } } export class RubyClass extends RubyObject { constructor(_type=undefined) { super(_type); this.public_imethods = {}; this.private_imethods = {}; this.protected_imethods = {}; this.base = null; } copy() { let cls = new RubyClass(); cls.public_imethods = {...this.public_imethods}; cls.private_imethods = {...this.private_imethods}; cls.protected_imethods = {...this.protected_imethods}; cls.set_base(this.get_base()); cls.name = this.name; return cls; } subclass(name) { let cls = new RubyClass(); cls.public_imethods = {}; cls.private_imethods = {}; cls.protected_imethods = {}; // This might be incorrect! cls.public_methods = {}; cls.private_methods = {}; cls.protected_methods = {}; cls.base = this; cls.name = name; return cls; } _get_bhier(n, sn) { // console.log(this[n], sn); if (sn in this[n]) { return this[n][sn]; } let bc = this.get_base(); if (!(bc instanceof Object)) { throw new exc.NoMethodError(sn); } return bc._get_bhier(n, sn); } _set_bhier(n, sn, v) { if (name in this[n]) { this[n][sn] = v; } let bc = this.get_base(); if (bc === undefined) { throw new exc.NoMethodError(sn); } bc._set_bhier(n, sn, v); } _collect_bhier(n) { let res = {}; let cr = this; while (1) { let collection = cr[n]; let collection_new = {}; for (let oname in collection) { if (collection.hasOwnProperty(oname)) { collection_new[oname] = function(...args) { return collection[oname].call(this, ...args) }; } } res = {...collection_new, ...res}; cr = cr.get_base(); if (cr === null) { break; } } return res; } get_public_imethod(name) { // Look for method in inheritance chain try { return this._get_bhier("public_imethods", name); } catch (e) { if (!(e instanceof exc.NoMethodError)) { throw e; } } // Look up method in extended modules for (let module of this.extended) { try { return this._module_imethod_wrapper(module.get_public_imethod(name), ctx); } catch (e) { if (!((e instanceof exc.NoType) || (e instanceof exc.NoMethodError))) { throw e; } } } throw new exc.NoMethodError(name); } get_private_imethod(name) { return this._get_bhier("private_imethods", name); } get_protected_imethod(name) { return this._get_bhier("protected_imethods", name); } // TODO: Figure out why these functions exist set_public_imethod(name, value) { this._set_bhier("public_imethods", name, value); } set_private_imethod(name, value) { this._set_bhier("private_imethods", name, value); } set_protected_imethod(name, value) { this._set_bhier("protected_imethods", name, value); } collect_public_imethods() { return this._collect_bhier("public_imethods"); } collect_private_imethods() { return this._collect_bhier("private_imethods"); } collect_protected_imethods() { return this._collect_bhier("protected_imethods"); } include(module) { this.included.push(module); } extend(module) { this.extended.push(module); } } BaseClass = new RubyClass(); BaseClass.type = BaseClass; BaseClass.name = "Class"; BaseClass.public_methods = { "new": function(env, ...args) { if (this.fast_new !== undefined) { return this.fast_new(env, ...args); } let result = this.methods("allocate")(env); result.methods("initialize")(env, ...args); return result; }, "allocate": function(env) { return new RubyObject(this); }, "copy": function(env) { return this.copy(); }, "class": function(env, other) { return this.get_type(); }, "superclass": function(env, other) { return this.get_base(); } }; BaseClass.public_imethods = { "initialize": function(env, ...args) { return env._T(env, null); } }; Module = new RubyClass(); Module.name = "Module"; Module.create = function(name) { let m = new RubyClass(Module); m.name = name; m.subclass = function (name) { throw new Error("Cannot subclass Module instance"); }; m.create = function (name) { throw new Error("Cannot create a Module from a Module instance; use Module.create instead"); }; m.get_type = function() { return Module; }; return m; }; Module.subclass = function (name) { throw new Error("Cannot subclass Module, use Module.create instead"); }; Module.get_type = function() { return BaseClass; }; Module.public_imethods = []; Module.private_imethods = []; Module.protected_imethods = [];var searchData= [ ['sconfig',['sConfig',['../a00109.html',1,'config']]], ['scontroller',['sController',['../a00097.html',1,'config']]], ['setbridgestability',['setBridgeStability',['../a00133.html#a19191b156161bd7a3978659329ceaad2',1,'RobotController']]], ['setcontact',['setContact',['../a00129.html#af0d391d121096fa6f2d214bb8910c0a1',1,'Robot']]], ['setdelay',['setDelay',['../a00129.html#a75e40c383e9191a17f25baa3aa5a35d8',1,'Robot']]], ['setid',['setId',['../a00129.html#a46b12a6c9386c0067f9f35b3e60a25f7',1,'Robot']]], ['setnbrobots',['setNbRobots',['../a00133.html#adf00a753bc750624e805f57f8998ad78',1,'RobotController']]], ['setrobotstate',['setRobotState',['../a00133.html#a797837410a2802b5d7399d132924ba2c',1,'RobotController']]], ['setscale',['setScale',['../a00133.html#a76d6bb1e93bb9523850370fdf76407c4',1,'RobotController']]], ['setspeed',['setSpeed',['../a00129.html#a0a1948c69efd8bce2487afdedb6f47f1',1,'Robot']]], ['setstate',['setState',['../a00129.html#aaf534f168d818112ae1f6440b329eb0a',1,'Robot']]], ['side',['side',['../a00047.html#afc015eff6557e84151d2e53b94375445',1,'Robot.h']]], ['srobot',['sRobot',['../a00101.html',1,'config']]], ['ssimulation',['sSimulation',['../a00093.html',1,'config']]], ['step',['step',['../a00133.html#ab2e4091fc2e47701cc5dbd7c2d9fc649',1,'RobotController']]], ['sterrain',['sTerrain',['../a00089.html',1,'config']]], ['swindow',['sWindow',['../a00105.html',1,'config']]] ]; parsegarden/Memexsrc/custom-lists/components/index.js export { default as ListSideBar } from './overview/sidebar/Index' (function() { 'use strict'; angular.module('angularRetinaExampleApp', ['ngRetina']) .controller('AngularRetinaExampleController', AngularRetinaExampleController); function AngularRetinaExampleController() { var vm = this; vm.image = 'images/angular.png'; } })(); 'use strict' const createPool = require('websocket-pool') const WebSocket = require('ws') const debug = require('debug')('hafas-client-rpc:ws-client') const createClientAdapter = require('../lib/client-adapter') const maxErrorsInArow = 3 const noConnectionAvailable = createPool.noConnectionAvailable.code const createWebSocketsRpcClient = (createScheduler, urls, cb) => { if (!Array.isArray(urls)) throw new Error('urls must be an array') const pool = createPool(WebSocket, createScheduler, { retry: { forever: true, factor: 1.5, minTimeout: 10 * 1000, maxTimeout: 10 * 60 * 1000 } }) const send = (msg) => { try { return pool.send(msg) } catch (err) { if (err && err.code === noConnectionAvailable) err.statusCode = 503 throw err } } const {facade, onMessage, onConnection} = createClientAdapter(send, maxErrorsInArow) pool.on('connection-open', onConnection) pool.on('message', (msg, connection) => { onMessage(msg.data, connection) }) for (let url of urls) pool.add(url) pool.once('open', () => cb(null, facade)) return pool } module.exports = createWebSocketsRpcClient AntumDeluge/debreate-web var searchData= [ ['main_2epy',['main.py',['../main_8py.html',1,'']]], ['mansect_2epy',['mansect.py',['../mansect_8py.html',1,'']]], ['manual_2epy',['manual.py',['../manual_8py.html',1,'']]], ['manuals_2epy',['manuals.py',['../manuals_8py.html',1,'']]], ['markdown_2epy',['markdown.py',['../markdown_8py.html',1,'']]], ['md5_2epy',['md5.py',['../md5_8py.html',1,'']]], ['menu_2epy',['menu.py',['../menu_8py.html',1,'']]], ['mime_2epy',['mime.py',['../mime_8py.html',1,'']]], ['moduleaccess_2epy',['moduleaccess.py',['../moduleaccess_8py.html',1,'']]] ]; export default { // 'mypurecloud.com': 'e88db007-526a-4f21-af25-81118183c37e', //Development Client ID 'mypurecloud.com': '26255f2c-6a85-43bf-8d27-7761057bc72d', 'mypurecloud.ie': '939ab4dd-109f-4120-ba9f-051b973b9ecc', 'mypurecloud.com.au': 'c8a4d721-3fbb-4f50-b3e0-aa49bf86ac87', 'mypurecloud.jp': '28dbeebd-8128-4fe0-8f42-f2eebb767a71' }import always from './always' import arity from './arity' import curry from './curry' const unshift = (array, ...args) => always(array)(array.unshift(...args)) export default curry(arity(2, unshift)) export const normalization = () => { return `X = scale(X)` } export const pca = () => { return `X = PCA(COMPONENTS).fit_transform(X)` } export const textCleaning = () => { return `data = data.str.strip().str.slice(0,200) data = data.replace('\\?|\\.|\\!|\\/|\\;|\\:|\\#', '', regex=True)` } export const paramsPca = (components) => { return `COMPONENTS = ${components}` }0 (function(){ var nmsReportsApp = angular .module('nmsReports') .controller("ContactUsResponseController", ['$scope', '$state', '$timeout', function($scope, $state, $timeout){ $scope.goBackToContactUsForm = function(){ $state.go('contactUs') } }]) })();login.js let lib = require('./lib') let db = require('./db') let bcrypt = require("bcrypt"); let serveSessionData = function (env) { lib.serveJson(env.res, { session: env.session, login: env.sessionData.login, firstName: env.sessionData.firstName, role: env.sessionData.role }) } module.exports = { handle: function (env) { switch (env.req.method) { case 'GET': serveSessionData(env) break case 'POST': db.userCollection.findOne({email: env.parsedPayload.login}, function (err, result1) { if (err || !result1) { lib.serveError(env.res, 401, 'authorization failed') } else { db.credentialCollection.findOne({user_id: result1._id}, function (err, result2) { if (!err || result2) { bcrypt.compare(env.parsedPayload.password, result2.password, function (err, res) { if (res) { env.sessionData.login = env.parsedPayload.login env.sessionData.firstName = result1.firstName env.sessionData.role = result2.role env.sessionData._id = result1._id serveSessionData(env) } else { lib.serveError(env.res, 401, 'authorization failed') } }) } else { lib.serveError(env.res, 401, 'authorization failed') } }) } }) break case 'DELETE': delete env.sessionData.login delete env.sessionData.firstName delete env.sessionData.role delete env.sessionData._id serveSessionData(env) break default: lib.serveError(env.res, 405, 'Method not implemented') return } } }module.exports = function(grunt, options){ var projectDev = options.projectDev; var projectDir = options.projectDir; return { options: { sourceMap: false, presets: ['es2015'] }, dist: { files: { '<%= projectDir %>/script.js': '<%= projectDev %>/script.js' } } }; }; shahbazshoukat/nextjs-learningservices/app-service.js import httpClient from '../helpers/http_client/http_client'; export const getApps = async () => { try { const response = await httpClient.get(`/api/v1/apps/`); return response && response.data ? response.data : []; } catch (error) { console.error("Failed to fetch apps:", error); return []; } }; export const getAppById = async (appId) => { try { const response = await httpClient.get(`/api/v1/apps/${appId}`); return response && response.data ? response.data : []; } catch (error) { console.error("Failed to fetch apps:", error); return []; } }; export const createNewApp = async (appData) => { console.log('createNewApp: ', appData) try { console.log('createNewApp: ', appData) const response = await httpClient.post(`/api/v1/apps/`, {}, { withCredentials: true }); return response && response.data ? response.data : []; } catch (error) { console.error("Failed to fetch apps:", error); return null; } }; export const updateAnApp = async (appId, appData) => { try { const response = await httpClient.put(`/api/v1/apps/${appId}`, appData); return response && response.data ? response.data : []; } catch (error) { console.error("Failed to fetch apps:", error); return []; } }; export const deleteAnApp = async (appId) => { try { const response = await httpClient.delete(`/api/v1/apps/${appId}`); return response && response.data ? response.data : []; } catch (error) { console.error("Failed to fetch apps:", error); return []; } }; browser/scripts/ui/uiDragAwareHelper.js0 /** * this helper allows any element to be dragged by mouse or touch and produce start/move/end events * var el = document.getElementById('test'), * d = new UIDragAware(el, function(){ return shouldStart(data) }) * d.detach() // remove your own event handlers if not removing element * * @emits uiDragstart|uiDragmove|uiDragend * * @param domNode * @param onStart optional callback test - if this returns false dragging is not enabled * @constructor */ var UIDragAwareHelper = function(domNode, onStart) { this.dragEvents = { start : 'uiDragstart', move : 'uiDragmove', end : 'uiDragend', remove : 'uiDragremove' } onStart = onStart || function() { return true } var that = this this.minDelta = 2 function _emit(node, eventName, data) { node.dispatchEvent(new CustomEvent(eventName, {detail: data})) } function makeEventData(data, currentPosition) { var op = data.startPosition, lp = data.lastPosition, o = data.startOffset return { touchId : data.touchId, pointer : data.pointer, position : {x: currentPosition.x, y: currentPosition.y}, lastPosition : {x: lp.x, y: lp.y}, startPosition : {x: op.x, y: op.y}, startOffset : {x: o.x, y: o.y}, delta : {x : (currentPosition.x - lp.x), y : (currentPosition.y - lp.y) }, startDelta : {x : (currentPosition.x - op.x), y : (currentPosition.y - op.y) } } } var _attached = false // prevent up() from executing more than once var up = function(data) { return function(e) { if (!_attached) return if (E2 && E2.ui) E2.ui.setDragging(false); domNode.removeEventListener(that.dragEvents.remove, data.up) document.removeEventListener('mousemove', data.move, true) document.removeEventListener('touchmove', data.move, true) document.removeEventListener('mouseup', data.up) document.removeEventListener('touchcancel', data.up) document.removeEventListener('touchend', data.up) _attached = false if (e.preventDefault) e.preventDefault() _emit(domNode, that.dragEvents.end, makeEventData(data, {x: data.lastPosition.x, y: data.lastPosition.y})) return true }} var move = function(data) { return function(e) { var t = e.touches ? e.touches[data.touchId] : e; var ed = makeEventData(data, {x: t.pageX, y : t.pageY}) if (Math.abs(ed.delta.x) + Math.abs(ed.delta.y) >= that.minDelta) { _emit(domNode, that.dragEvents.move, ed) data.lastPosition = ed.position } if(e.preventDefault) e.preventDefault() return true } // end closure } var down = function() { return function(e) { var touchId = 0 // @todo get correct touch id var t = (e.touches) ? e.touches[touchId] : e; var data = { touchId : touchId, pointer : t, lastPosition : { x: t.pageX, y: t.pageY }, startPosition : { x: t.pageX, y: t.pageY }, startOffset : { x: t.offsetX, y: t.offsetY } } if (!onStart(makeEventData(data, {x: t.pageX, y: t.pageY}))) return true data.up = up(data) data.move = move(data) document.addEventListener('touchend', data.up) document.addEventListener('touchcancel', data.up) document.addEventListener('mouseup', data.up) document.addEventListener('touchmove', data.move, true) document.addEventListener('mousemove', data.move, true) domNode.addEventListener(that.dragEvents.remove, data.up) _attached = true if(e.preventDefault) e.preventDefault() if (E2 && E2.ui) E2.ui.setDragging(true); _emit(domNode, that.dragEvents.start, data) data.move(e) return true } } var _down = down() this.attach = function() { domNode.addEventListener('touchstart', _down) domNode.addEventListener('mousedown', _down) } this.detach = function() { domNode.dispatchEvent(new CustomEvent(that.dragEvents.remove)) // force detach handlers domNode.removeEventListener('mousedown', _down) domNode.removeEventListener('touchstart', _down) } this.attach() }const config = { verbose: true, testURL: 'http://localhost/', moduleNameMapper: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/.erb/mocks/fileMock.js', '\\.(css|less|sass|scss)$': 'identity-obj-proxy', '^@main/(.*)$': '/src/main/$1', '^@renderer/(.*)$': '/src/renderer/$1', }, transformIgnorePatterns: [ '/node_modules/(?!(lodash-es|@main|@renderer)/.*)', ], moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json'], moduleDirectories: ['node_modules', 'build/app/node_modules'], setupFiles: ['./.erb/scripts/check-build-exists.js'], }; module.exports = config; TestesDeFixacaoDoConteudo/exercitandoBuscaTecnologia.js let usuarios = [ // AQUI É UM ARRAY COM UM CONJUNTO DE OBJETOS {nome: 'JONAS', tecnologias: ['HTML','CSS']}, {nome: 'BARBARA', tecnologias: ['JAVA', 'ANDROID']}, {nome: 'BARBARA', tecnologias: ['JAVA', 'ANDROID']}] function listarUser(user) { for (let i = 0; i < user.length; i++) { console.log(`O USUARIO ${user[i].nome},USA A TECNOLOGIA ${listarTecnogias(user[i].tecnologias)} `); } } function listarTecnogias(tecnologia) { let nameTec = ''; for(let i = 0; i < tecnologia.length; i++){ nameTec = nameTec +" " + tecnologia[i] } return nameTec } listarUser(usuarios)jojow/node-mrsw-locklib/MRSWLock.js var debug = require('debug')('mrsw-lock'); var async = require('async'); var _ = require('lodash'); var uuid = require('uuid'); var RedisPool = require('redis-poolify'); var clientPool = new RedisPool(); var stringifyObj = function(obj) { if (!_.isPlainObject(obj) && !_.isArray(obj)) return obj; var arr = _.map(obj, function(val, key) { if (_.isPlainObject(val) || _.isArray(val)) return key + ':' + stringifyObj(val); else return key + ':' + val; }); return _(arr).sort().value().toString(); }; var releaseScript = 'if redis.call("get", KEYS[1]) == ARGV[1]\n\ then\n\ return redis.call("del", KEYS[1])\n\ else\n\ return 0\n\ end'; var MRSWLock = function(config) { debug('new instance of MRSWLock', config); config = config || {}; var maxReadLockTime = config.maxReadLockTime || 240; var maxWriteLockTime = config.maxWriteLockTime || 30; var baseDelay = config.baseDelay || 0.1; var delayOffsetMin = config.delayOffsetMin || 0.01; var delayOffsetMax = config.delayOffsetMax || 0.1; var maxRetries = config.maxRetries || 3; this.readLock = function(id, callback) { var token = uuid.v4(); var idStr = stringifyObj(id); var readKey = 'read:' + idStr + ':' + token; var writeKey = 'write:' + idStr; debug('try to lock for read', id, token); async.waterfall([ async.apply(clientPool.acquire, config), function(client, cb) { var retries = 0; var delay = baseDelay; var lock = function(timeout) { setTimeout(function() { client.multi(). set([ readKey, 'anyvalue', 'NX', 'EX', maxReadLockTime ]). get(writeKey). exec(function(err, replies) { retries++; delay = (delay * 2) + _.random(delayOffsetMin, delayOffsetMax); var handleErr = function(err) { client.del(readKey, function(delErr, reply) { if (delErr) console.error(delErr); cb(err); clientPool.release(config, client); }); }; if (err) return handleErr(err); else if ((replies[0] === 'OK' || replies[0] === 1) && replies[1] === null) cb(null, token); else if (retries === maxRetries) return handleErr(new Error('Cannot get read lock after ' + retries + ' retries')); else return lock(delay); debug('locked for read', id, token); clientPool.release(config, client); }); }, timeout * 1000); }; lock(0); } ], callback); }; this.writeLock = function(id, callback) { var token = uuid.v4(); var idStr = stringifyObj(id); var readKey = 'read:' + idStr + ':*'; var writeKey = 'write:' + idStr; debug('try to lock for write', id, token); async.waterfall([ async.apply(clientPool.acquire, config), function(client, cb) { var retries = 0; var delay = baseDelay; var lock = function(timeout) { setTimeout(function() { client.multi(). set([ writeKey, token, 'NX', 'EX', maxWriteLockTime ]). keys(readKey). exec(function(err, replies) { retries++; delay = (delay * 2) + _.random(delayOffsetMin, delayOffsetMax); var delWriteKey = function(cb) { client.eval([ releaseScript, 1, writeKey, token ], function(evalErr, reply) { if (evalErr) console.error(evalErr); cb(); }); }; var handleErr = function(err) { delWriteKey(function() { cb(err); clientPool.release(config, client); }); }; if (err) return handleErr(err); else if ((replies[0] === 'OK' || replies[0] === 1) && _.size(replies[1]) === 0) cb(null, token); else if (retries === maxRetries) return handleErr(new Error('Cannot get write lock after ' + retries + ' retries')); else return delWriteKey(function() { lock(delay); }); debug('locked for write', id, token); clientPool.release(config, client); }); }, timeout * 1000); }; lock(0); } ], callback); }; this.readRelease = function(id, token, callback) { var idStr = stringifyObj(id); var readKey = 'read:' + idStr + ':' + token; debug('try to release read lock', id, token); async.waterfall([ async.apply(clientPool.acquire, config), function(client, cb) { client.del(readKey, function(err, reply) { if (err) { debug('error while releasing read lock', err, id, token); return cb(err); } else if (reply === 'OK' || reply === 1) { cb(null, token); } else { cb(null); } debug('read lock released', id, token); clientPool.release(config, client); }); } ], callback); }; this.writeRelease = function(id, token, callback) { var idStr = stringifyObj(id); var writeKey = 'write:' + idStr; debug('try to release write lock', id, token); async.waterfall([ async.apply(clientPool.acquire, config), function(client, cb) { client.eval([ releaseScript, 1, writeKey, token ], function(err, reply) { if (err) { debug('error while releasing write lock', err, id, token); return cb(err); } else if (reply === 'OK' || reply === 1) { cb(null, token); } else { cb(null); } debug('write lock released', id, token); clientPool.release(config, client); }); } ], callback); }; }; module.exports = MRSWLock; 1-10 'use strict' const { Place } = require('@gotandajs/models') exports.findByEventPlaces = (eventPlaces) => { const placeIds = eventPlaces.map(eventPlace => eventPlace.placeId) return Place.findAll({ where: { id: placeIds } }) } brentrobbins/gatsby-mailsrc/util/parse-payload.js function parsePayload(payload) { if (typeof window === `undefined`) { return `` } return atob(payload.data.replace(/-/g, '+').replace(/_/g, '/')) } export default parsePayload voxace/mullumtas const mongoose = require('mongoose'); const Schema = mongoose.Schema; const resourceSchema = new Schema({ title: { type: String, required: true }, type: { type: String, required: true }, order: { type: Number, required: true }, isActive: { type: Boolean, default: true }, link: { type: String, required: true }, }); const Resource = mongoose.model('Resource', resourceSchema); module.exports = Resource; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sizeDependencies = void 0; var _dependenciesMatrixGenerated = require("./dependenciesMatrix.generated.js"); var _dependenciesTypedGenerated = require("./dependenciesTyped.generated.js"); var _factoriesNumber = require("../../factoriesNumber.js"); /** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ var sizeDependencies = { matrixDependencies: _dependenciesMatrixGenerated.matrixDependencies, typedDependencies: _dependenciesTypedGenerated.typedDependencies, createSize: _factoriesNumber.createSize }; exports.sizeDependencies = sizeDependencies;mray190/devicejs-ngtest/testQueryParser.js /* * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ var expect = require('expect.js'); var should = require('should'); var shouldPromised = require('should-promised'); var query = require('../src/core/selection'); describe('query.Tokenizer', function() { function checkTokenStream(string, expectedTokenStream) { var tokenizer = new query.Tokenizer(string); expectedTokenStream.forEach(function(expectedNextToken) { if(expectedNextToken instanceof Error) { (function() { tokenizer.next(); }).should.throw(expectedNextToken); } else { tokenizer.next(); tokenizer.getCurrentToken().should.be.eql(expectedNextToken); expectedNextToken.__proto__.should.be.eql(tokenizer.getCurrentToken().__proto__) } }); if(!(expectedTokenStream[expectedTokenStream.length-1] instanceof Error)) { tokenizer.next(); should.equal(tokenizer.getCurrentToken(), null); } } it('should be able to tokenize a valid unnested expression regardless of whitespace', function() { checkTokenStream('group="" and id="hi" or interface = "myinterface" and type= "mytype" ', [ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"') ]); }); it('should be able to tokenize a valid nested expression regardless of whitespace', function() { checkTokenStream('group="" and ( id="hi" or interface = "myinterface" and type= "mytype" ) ', [ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('('), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"'), new query.TerminalToken(')'), ]); }); it('should be tokenize a string that is not a valid expression but only contains valid tokens', function() { checkTokenStream('group="" and ( ( ) id "hi" or interface "myinterface" type "mytype" = ) ', [ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('('), new query.TerminalToken('('), new query.TerminalToken(')'), new query.TerminalToken('id'), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.StringToken('"myinterface"'), new query.TerminalToken('type'), new query.StringToken('"mytype"'), new query.TerminalToken('='), new query.TerminalToken(')') ]); }); it('should be able to tokenize a valid unnested expression', function() { checkTokenStream('group="" and id="hi"', [ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), ]); }); it('should throw an "Invalid token" exception when an improperly formatted string is used', function() { checkTokenStream('group=" and id="hi"', [ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('" and id="'), new Error('Invalid token') ]); }); it('an empty string should result in no tokens produced', function() { checkTokenStream('', []); }); it('an string with only whitespace should result in no tokens', function() { checkTokenStream(' \n \t \f', []); }); }); describe('query.Parser', function() { var MockTokenizer = function(tokenSequence) { this.tokenSequence = tokenSequence; this.currentTokenIndex = -1; }; MockTokenizer.prototype.next = function() { // return same as peek token but advance index this.currentTokenIndex += 1; var token = this.getCurrentToken(); return token; }; MockTokenizer.prototype.getCurrentToken = function() { // return next token without advancing it. // multiple calls to peekToken return the same // token. return this.tokenSequence[this.currentTokenIndex] || null; }; it('should parse simple checks', function() { // simple check var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), ])); parser.parse().should.be.eql(new query.StringCheckNode('group', '')); // negated check var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('not'), new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), ])); parser.parse().should.be.eql(new query.NotNode(new query.StringCheckNode('group', ''))); // simple check in parentheses var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('('), new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken(')'), ])); parser.parse().should.be.eql(new query.StringCheckNode('group', '')); // simple negated check in parentheses var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('('), new query.TerminalToken('not'), new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken(')'), ])); parser.parse().should.be.eql(new query.NotNode(new query.StringCheckNode('group', ''))); // simple negated check in parentheses 2 var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('not'), new query.TerminalToken('('), new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken(')'), ])); parser.parse().should.be.eql(new query.NotNode(new query.StringCheckNode('group', ''))); }); it('should parse simple boolean and expression', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"') ])); parser.parse().should.be.eql(new query.AndNode( new query.StringCheckNode('group', ''), new query.StringCheckNode('id', 'hi') )); }); it('should parse simple boolean or expression', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('or'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.TerminalToken('*') ])); parser.parse().should.be.eql(new query.OrNode( new query.StringCheckNode('group', ''), new query.WildcardCheckNode('id') )); }); it('should parse expressions with multiple ands and ors in sequence', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"') ])); parser.parse().should.be.eql(new query.OrNode( new query.AndNode( new query.StringCheckNode('group', ''), new query.StringCheckNode('id', 'hi') ), new query.AndNode( new query.StringCheckNode('interface', 'myinterface'), new query.StringCheckNode('type', 'mytype') ) )); }); it('should throw parse error if checks are not seperated by boolean operators', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), //new query.TerminalToken('and'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"') ])); (function() { parser.parse(); }).should.throw(new Error('Parse error')); var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), //new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"') ])); (function() { parser.parse(); }).should.throw(new Error('Parse error')); var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), //new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"') ])); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should give precedence to operations grouped in parentheses', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('('), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), new query.TerminalToken(')'), new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"') ])); parser.parse().should.be.eql(new query.AndNode( new query.StringCheckNode('group', ''), new query.AndNode( new query.OrNode( new query.StringCheckNode('id', 'hi'), new query.StringCheckNode('interface', 'myinterface') ), new query.StringCheckNode('type', 'mytype') ) )); }); it('should throw parse error if a predicate in parentheses is not finished with a close parenthesis', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.StringToken('""'), new query.TerminalToken('and'), new query.TerminalToken('('), new query.TerminalToken('id'), new query.TerminalToken('='), new query.StringToken('"hi"'), new query.TerminalToken('or'), new query.TerminalToken('interface'), new query.TerminalToken('='), new query.StringToken('"myinterface"'), //new query.TerminalToken(')'), new query.TerminalToken('and'), new query.TerminalToken('type'), new query.TerminalToken('='), new query.StringToken('"mytype"') ])); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should fail on empty tokenizer', function() { var parser = new query.Parser(new MockTokenizer([ ])); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should fail if check uses invalid property', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('property'), new query.TerminalToken('='), new query.StringToken('""'), ])); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should fail if check uses invalid value', function() { var parser = new query.Parser(new MockTokenizer([ new query.TerminalToken('group'), new query.TerminalToken('='), new query.TerminalToken('#'), ])); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); }); describe('query.Parser + query.Tokenizer', function() { it('should parse simple checks', function() { // simple check var parser = new query.Parser(new query.Tokenizer('group=""')); parser.parse().should.be.eql(new query.StringCheckNode('group', '')); // negated check var parser = new query.Parser(new query.Tokenizer('not group=""')); parser.parse().should.be.eql(new query.NotNode(new query.StringCheckNode('group', ''))); // simple check in parentheses var parser = new query.Parser(new query.Tokenizer('(group="")')); parser.parse().should.be.eql(new query.StringCheckNode('group', '')); // simple negated check in parentheses var parser = new query.Parser(new query.Tokenizer('(not group="")')); parser.parse().should.be.eql(new query.NotNode(new query.StringCheckNode('group', ''))); // simple negated check in parentheses 2 var parser = new query.Parser(new query.Tokenizer('not(group="")')); parser.parse().should.be.eql(new query.NotNode(new query.StringCheckNode('group', ''))); }); it('should parse simple boolean and expression', function() { var parser = new query.Parser(new query.Tokenizer('group="" and id="hi"')); parser.parse().should.be.eql(new query.AndNode( new query.StringCheckNode('group', ''), new query.StringCheckNode('id', 'hi') )); }); it('should parse simple boolean or expression', function() { var parser = new query.Parser(new query.Tokenizer('group="" or id=*')); parser.parse().should.be.eql(new query.OrNode( new query.StringCheckNode('group', ''), new query.WildcardCheckNode('id') )); }); it('should parse expressions with multiple ands and ors in sequence', function() { var parser = new query.Parser(new query.Tokenizer('group="" and id="hi" or interface="myinterface" and type="mytype"')); parser.parse().should.be.eql(new query.OrNode( new query.AndNode( new query.StringCheckNode('group', ''), new query.StringCheckNode('id', 'hi') ), new query.AndNode( new query.StringCheckNode('interface', 'myinterface'), new query.StringCheckNode('type', 'mytype') ) )); }); it('should produce identical stringified forms when asts are flattened for equivalent expressions', function() { var normalizedString = '( group="" and id="hi" and interface="myinterface" and type="mytype" )'; var parser1 = new query.Parser(new query.Tokenizer('group="" and id="hi" and interface="myinterface" and type="mytype"')); var parser2 = new query.Parser(new query.Tokenizer('type="mytype" and group="" and interface="myinterface" and id="hi"')); var parser3 = new query.Parser(new query.Tokenizer('(group="" and id="hi") and (interface="myinterface" and type="mytype")')); var p1 = parser1.parse(); var p2 = parser2.parse(); var p3 = parser3.parse(); p1.toNormalizedString().should.be.eql(p2.toNormalizedString()); p2.toNormalizedString().should.be.eql(p3.toNormalizedString()); p3.toNormalizedString().should.be.eql(normalizedString); p1.toString().should.not.be.eql(p2.toString()); p2.toString().should.not.be.eql(p3.toString()); p1.flatten(); p2.flatten(); p3.flatten(); p1.toString().should.be.eql(p2.toString()); p2.toString().should.be.eql(p3.toString()); p3.toString().should.be.eql(normalizedString); }); it('should throw parse error if checks are not seperated by boolean operators', function() { var parser = new query.Parser(new query.Tokenizer('group="" id="hi" or interface="myinterface" and type="mytype"')); (function() { parser.parse(); }).should.throw(new Error('Parse error')); var parser = new query.Parser(new query.Tokenizer('group="" and id="hi" interface="myinterface" and type="mytype"')); (function() { parser.parse(); }).should.throw(new Error('Parse error')); var parser = new query.Parser(new query.Tokenizer('group="" and id="hi" or interface="myinterface" type="mytype"')); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should give precedence to operations grouped in parentheses', function() { var parser = new query.Parser(new query.Tokenizer('group="" and ( id="hi" or interface="myinterface") and type="mytype"')); parser.parse().should.be.eql(new query.AndNode( new query.StringCheckNode('group', ''), new query.AndNode( new query.OrNode( new query.StringCheckNode('id', 'hi'), new query.StringCheckNode('interface', 'myinterface') ), new query.StringCheckNode('type', 'mytype') ) )); }); it('should throw parse error if a predicate in parentheses is not finished with a close parenthesis', function() { var parser = new query.Parser(new query.Tokenizer('group="" and ( id="hi" or interface="myinterface" and type="mytype"')); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should fail on empty tokenizer', function() { var parser = new query.Parser(new query.Tokenizer('\t\n ')); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should fail if check uses invalid property', function() { var parser = new query.Parser(new query.Tokenizer('property=""')); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); it('should fail if check uses invalid value', function() { var parser = new query.Parser(new query.Tokenizer('group=#')); (function() { parser.parse(); }).should.throw(new Error('Parse error')); }); }); /* global BigInt */ const double = require('.') const assert = require('assert') for (var i = 0; i < 10000; i++) { var a = BigInt(double().toFixed(52).replace('.', '')) var b = BigInt(double().toFixed(52).replace('.', '')) assert.ok(a / double.DISTANCE < double.POINTS) assert.ok(b / double.DISTANCE < double.POINTS) assert.ok(a % double.DISTANCE === 0n) assert.ok(b % double.DISTANCE === 0n) assert.ok((a - b) % double.DISTANCE === 0n) } 'use strict'; const Alexa = require('alexa-sdk'); const service = require('./recipe.service.js')('RECIPE_PUPPY'); // APP_ID not required const APP_ID = undefined; // language definitions const SAY = { SKILL_NAME: 'Hotplate', RESULTS: "Ok, I found multiple recipes. You can say another ingredient, or say done.", NO_RESULTS: "I'm sorry, I can't find any recipes with those ingredients.", DONE: "Ok, I have sent the recipes to your Alexa app.", HELP_MESSAGE: 'You can search for recipes by starting with an ingredient, or, you can say exit... What can I help you with?', HELP_REPROMPT: 'What can I help you with?', STOP_MESSAGE: 'Goodbye!', ERROR_MESSAGE: 'Oh snap, something broke.' }; // alexa intent handlers const handlers = { // built in intents 'LaunchRequest': function () { this.emit('RecipeSearch'); }, 'Unhandled': function () { this.emit(':tell', SAY.ERROR_MESSAGE); }, 'AMAZON.HelpIntent': function () { const speechOutput = SAY.HELP_MESSAGE; const reprompt = SAY.HELP_MESSAGE; this.emit(':ask', speechOutput, reprompt); }, 'AMAZON.CancelIntent': function () { this.emit(':tell', SAY.STOP_MESSAGE); }, 'AMAZON.StopIntent': function () { this.emit(':tell', SAY.STOP_MESSAGE); }, 'SessionEndedRequest': function () { this.attributes['keys'] = ''; this.emit(':tell', SAY.STOP_MESSAGE); }, // Custom intents 'RecipeSearch': recipeSearch, 'Done': recipeComplete, }; // Search for recipes based on ingredient function recipeSearch() { console.log('Recipe search called'); let params = [ this.event.request.intent.slots.INGONE.value, this.event.request.intent.slots.INGTWO.value, this.event.request.intent.slots.INGTHREE.value ]; console.log(this.event.request.intent.slots); // merge keys from session if (typeof this.attributes['keys'] === 'string') { const prevKeys = this.attributes['keys'].split(','); if (prevKeys.length) { params = params.concat(prevKeys); } } const keys = params.filter(val => { return val; }).join(','); // store the search keys if (keys.length > 0) { this.attributes['keys'] = keys; } console.log(keys); service.count(keys) .then(response => { if (response.count > 0) { this.emit(':ask', SAY.RESULTS.replace('{0}', response.count)); } else { this.emit(':tell', SAY.NO_RESULTS); this.attributes['keys'] = ''; } }).catch(err => { console.log(err); self.emit('Unhandled'); }); } // Send the recipes to the consumer function recipeComplete() { console.log('Done called'); const keys = this.attributes['keys']; service.search(keys) .then(response => { const title = `${response.count} recipes with ${keys}`; const content = []; for (let i = 0; i < response.recipes.length; i++) { const r = response.recipes[i]; content.push(`${r.title}`); } const output = content.join('\n'); this.emit(':tellWithCard', SAY.DONE, title, output); }); this.attributes['keys'] = ''; } // Register with alexa service function registerAlexa(event, context, callback) { var alexa = Alexa.handler(event, context); alexa.APP_ID = APP_ID; alexa.registerHandlers(handlers); alexa.execute(); } exports.handler = registerAlexa; 1-10 function getProp(name, _default) { return model._properties[name] ? model._properties[name].value : (_default || model._styles[name]); }idmore/idmore-academy-web "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { title: "Idmore Academy - More things available", description: "Here we are not only focused on making tech products. But it also makes technology accessible, affordable and easy for everyone to learn." };Dismiss-New-Follow-Feature-Popup-On-Active-Sites/Dismiss_New_Follow_Feature_Popup_On_Active_Sites.user.js10-100 // ==UserScript== // @name SE: Dismiss New Follow Feature Popup On Active Sites // @namespace https://github.com/makyen/StackExchange-userscripts // @version 1.1.0 // @description Dismiss the popup notification of the new follow feature on all sites you have an account on. // @author Makyen // @match https://stackexchange.com/dismiss-follow-notification // @require https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/gm4-polyfill.js // @grant GM_xmlhttpRequest // @grant GM.xmlHttpRequest // @run-at document-idle // @connect stackexchange.com // @connect stackoverflow.com // @connect superuser.com // @connect serverfault.com // @connect askubuntu.com // @connect stackapps.com // @connect mathoverflow.net // ==/UserScript== /* globals */ // eslint-disable-line no-unused-vars, no-redeclare //Once installed, navigate to // https://stackexchange.com/dismiss-follow-notification //While on that page, the userscript will go through the sites on which you have accounts. //Due to SE rate limiting, and to avoid the possibility of SE imposing a rate-limit block on your IP, //the script waits 5 seconds between each site. Most SE sites have a Meta site, so, currently, that's //up to 344 different sites, which will take up to 29 minutes. (function() { 'use strict'; const SE_ACTION_DELAY = 5000; if (document.readyState === 'loading') { window.addEventListener('DOMContentLoaded', afterLoaded); } else { afterLoaded(); } function gmXmlHttpRequestAsPromise(details) { return new Promise((resolve, reject) => { ['onerror', 'ontimeout', 'onabort'].forEach((type) => { const origHandler = details[type]; details[type] = function(response) { if (typeof origHandler === 'function') { origHandler(response); } //console.error('gmXmlHttpRequestAsPromise:', type, 'response:', response); response.gmError = type; reject(response); }; }); const origOnLoad = details.onload; function onload(response) { if (typeof origOnLoad === 'function') { origOnLoad(response); } if (response.status !== 200) { //console.error('gmXmlHttpRequestAsPromise: onload status !== 200: response:', response); response.gmError = 'status !== 200'; reject(response); } else { resolve(response); } } details.onload = onload; GM.xmlHttpRequest(details); }); } function afterLoaded() { const parser = new DOMParser(); let thens = Promise.resolve(); const globalUID = document.querySelector('.my-profile').href.match(/\d+/)[0]; const apiKey = '; function setFollowNoticeSeenFlagIgnoreErrors(url, fkey, userId) { return gmXmlHttpRequestAsPromise({ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Origin': url, 'Referer': url + '/q/1', 'X-Requested-With': 'XMLHttpRequest', }, url: url + '/users/toggle-flag/512/true', data: `fkey=${fkey}&userId=${userId}`, }).then((followResponse) => { const status = followResponse.status === 200 && followResponse.response === '{"hasFlags":true}' ? 'success' : 'fail'; console.log('Set follow notice seen for site:', url, 'status:', status); if (status !== 'success') { console.log('followResponse:', followResponse); } }, (errorResponse) => { console.error('Failed to set follow notice seen for site:', url, 'errorResponse:', errorResponse); return Promise.resolve(); }); } function delay(time, delayedFunction) { //Return a Promise which is resolved after the specified delay and any specified function is called. // Any additional arguments are passed to the delayedFunction and the return value from that function // is what this Promise resolves as. This can chain an additional Promise. var mainArgs = arguments; //Needed due to a bug in a browser, I don't remember which one. See the GM4 polyfill merged PRs. return new Promise((resolve) => { setTimeout(() => { if (typeof delayedFunction === 'function') { //Using .slice(), or other Array methods, on arguments prevents optimization. var args = []; for (var index = 2; index < mainArgs.length; index++) { args.push(mainArgs[index]); } resolve(delayedFunction.apply(null, args)); } else { resolve(); } }, (time ? time : 0)); }); } const contentDiv = document.querySelector('.content-page.leftcol'); function setProcessingDisplay(index, total, url) { contentDiv.textContent = `Processing ${index}/${total}: ${url.replace('https://', '')}`; } function getJSONAjax(url) { return gmXmlHttpRequestAsPromise({ method: 'GET', url, }).then((response) => JSON.parse(response.responseText)); } function getItemsFromHasMorePagesWithBackoff(baseUrl, startPage, endPage) { //This will return a Promise which resolves with the "items" from every page from an AJAX URL which implements // a JSON response containing // an array "items", and a "has_more" boolean property in the base Object. It also implements a backoff // if the API response contains a "backoff" property with the number of seconds which need to be backed off. // If endPage is not provided, or is -1, then all items from all pages until "has_more" is false will be returned. // Given that this could be a huge number of pages, doing that should be only done with significant care. function getUrlWithPage(url, urlPage) { return `${url}&page=${urlPage}`; } startPage = typeof startPage === 'number' ? startPage : 1; endPage = typeof endPage === 'number' ? endPage : -1; let items = []; return new Promise((resolve, reject) => { function getItemsFromAPageAndContinue(page) { //Should also handle running out of quota. //Given that we are waiting to get the response from the previous page prior to requesting the next one, // it is assumed that takes long enough to prevent us from exceeding the 30 requests/s hard limit on the SE API. getJSONAjax(getUrlWithPage(baseUrl, page)) .then((jsonResponse) => { items = items.concat(jsonResponse.items || []); if (jsonResponse.has_more && endPage > 0 && page < endPage) { const backoff = jsonResponse.backoff ? jsonResponse.backoff * 1000 : 0; setTimeout(getItemsFromAPageAndContinue, backoff, page + 1); } else { resolve(items); } }, (error) => { //There is currently no actual error handling. //We should handle at least some errors here, because the SE API can give an error instead of a backoff, particularly if // the endpoint is in use by something else on the same IP address. //Pass the error on, but provide enough information such that the requests which succeeded are not wasted, and it's possible // to recover from the error (i.e. could retry from the current state). reject({// eslint-disable-line prefer-promise-reject-errors error, startPage, endPage, page, items, }); }); } getItemsFromAPageAndContinue(startPage); }); } //Get the list of sites on which the user has accounts. //Currently, 2020-03, there are < 180 SE sites, so we need, at most, 2 pages of 100. getItemsFromHasMorePagesWithBackoff(`https://api.stackexchange.com/2.2/users/${globalUID}/associated?pagesize=100&filter=!6PU2XEFMADgs1&key=${apiKey}`, 1, 10) .then((sites) => { let totalSites = sites.length; let siteProcessing = 0; sites.forEach(({user_id, site_url}) => { //Convert the site URL to a URL for the site's Meta. let metaSiteURL = site_url .replace('.stackexchange', '.meta.stackexchange') .replace('stackoverflow', 'meta.stackoverflow') .replace('superuser', 'meta.superuser') .replace('serverfault', 'meta.serverfault') .replace('mathoverflow', 'meta.mathoverflow') .replace('askubuntu', 'meta.askubuntu'); if (metaSiteURL === site_url || site_url === 'https://meta.stackexchange.com') { metaSiteURL = ''; } if (metaSiteURL) { totalSites++; } //Add this site and its Meta, if there is one, to the Promise chain. thens = thens.then(() => { siteProcessing++; setProcessingDisplay(siteProcessing, totalSites, site_url); //The fkey is not the same on all sites. Thus, to be sure, we get the fkey for each site. return gmXmlHttpRequestAsPromise({ method: 'GET', url: site_url, }).then((siteResponse) => { //Use the browser to parse the site's HTML. const siteAsDOM = parser.parseFromString(siteResponse.responseText, 'text/html'); const siteFkey = siteAsDOM.querySelector('input[name="fkey"]').value; //We now have all the information we need in order to send the POST to the site and its Meta. return setFollowNoticeSeenFlagIgnoreErrors(site_url, siteFkey, user_id) .then(() => { if (metaSiteURL) { return delay(SE_ACTION_DELAY).then(() => { siteProcessing++; setProcessingDisplay(siteProcessing, totalSites, metaSiteURL); setFollowNoticeSeenFlagIgnoreErrors(metaSiteURL, siteFkey, user_id); }); } }, () => delay(SE_ACTION_DELAY)) //Ignore errors and continue. //In order to avoid SE rate limiting, or a rate violation ban, delay 5s between each site. .then(() => delay(SE_ACTION_DELAY)); }); }); }); //All sites are now in the Promise chain. Update the display after everything is done. thens = thens.then(() => { setProcessingDisplay(siteProcessing, totalSites, 'ALL DONE'); }); }); } })(); cheminfo/dereplication import mlMedian from 'ml-array-median'; import median from '../median'; describe('median', () => { it('should return 3', () => { let a = [1, 2, 3, 4, 5]; expect(median(a, a.length)).toStrictEqual(3); }); it('even length array', () => { let a = [1, 2, 3, 4, 5, 5]; expect(median(a, a.length)).toStrictEqual(3); }); it('array with some values not pushed', () => { let a = [1, 2, 3, 4]; expect(median(a, a.length + 2)).toStrictEqual(3); }); it('median is the default value', () => { let a = [1, 2, 3]; expect(median(a, a.length + 4)).toStrictEqual(7); }); it('compare with ml-array-median (wicked test)', () => { let a = [1, 2, 3]; let b = [1, 2, 3, 5, 5, 5, 5]; expect(median(a, a.length + 4)).toStrictEqual(7); expect(mlMedian(b)).toStrictEqual(5); }); it('check ml-array-median behavior', () => { let a = [1, 2, 3, 4, 5, 5]; let commonResult = 3; expect(median(a, a.length)).toStrictEqual(commonResult); expect(mlMedian(a)).toStrictEqual(commonResult); }); it('check ml-array-median behavior 2', () => { let a = [1, 2, 3, 4, 5, 5, 5]; let commonResult = 4; expect(median(a, a.length)).toStrictEqual(commonResult); expect(mlMedian(a)).toStrictEqual(commonResult); }); it('check ml-array-median behavior 3', () => { let a = [1, 2]; let commonResult = 1; expect(median(a, a.length)).toStrictEqual(commonResult); expect(mlMedian(a)).toStrictEqual(commonResult); }); }); src/assets/icons.js import { faBars } from '@fortawesome/free-solid-svg-icons'; const icons = [faBars]; export default icons; 0 import React, { Component } from 'react'; import {Grid, Row, Col, Button, Form, FormGroup, FormControl, ControlLabel} from 'react-bootstrap'; import {requestOptions} from '../helpers/requestOptions'; import FlashMessage from './flashMessage'; class Generator extends Component { constructor(props) { super(props); this.state = { creatingPlaylist: false, playlistCompleted: false, showFlashMessage: false, flashType: '', flashMessage: '', }; this.handleOnClick = this.handleOnClick.bind(this); this.handleDismiss = this.handleDismiss.bind(this); this.handleShow = this.handleShow.bind(this); } handleDismiss() { this.setState({showFlashMessage: false}); } handleShow() { this.setState({showFlashMessage: true}); } async handleOnClick(event) { event.preventDefault(); this.setState({creatingPlaylist: true}); this.setState({playlistCompleted: false}); let playlist_name = event.target.elements.playlistName.value; if (playlist_name === '') playlist_name = 'PhiCloud'; const data = { access_token: localStorage.getItem('access_token'), user_id: this.props.username, playlist_name }; const response = await fetch('/api/generate-playlist', requestOptions(data, 'POST')); const json = await response.json(); if (response.status === 401) { this.setState({showFlashMessage: true}); this.setState({flashType: 'danger'}); this.setState({flashMessage: 'You encountered an error. Please try again!'}); } else if (response.status === 502) { this.handleOnClick(); } else { this.setState({creatingPlaylist: false}); this.setState({playlistCompleted: true}); this.setState({showFlashMessage: true}); this.setState({flashType: 'success'}); this.setState({flashMessage: 'Your playlist was successfully created!'}); } console.log(json); } generatePlaylist(buttonText) { return (

Automatically Generate Playlist

Name your playlist
) } render() { let buttonText = 'Create Playlist!'; let toRender = ''; if (this.state.creatingPlaylist) { buttonText = 'Creating playlist...'; } if (this.state.playlistCompleted) { buttonText = 'Create Playlist!'; toRender = } else { toRender = ''; } return (

Automatically Generate Playlist

Name your playlist
{toRender}
); } } export default Generator; kumabook/musicfav-cloud const gulp = require('gulp'); const eslint = require('gulp-eslint'); gulp.task('lint', () => gulp.src(['web/js/**/*.{js,jsx}', 'web/test/**/*.{js,jsx}']) .pipe(eslint({ fix: true})) .pipe(eslint.format()) .pipe(eslint.failAfterError()) ); gulp.task('default', ['lint'], function () {}); "use strict"; /* Callbacks: A callback is a function or method that is given as an argument to another function to be called at some point by that function. */ function addTwoNumbers(first, second) { return (first + second); } window.alert(addTwoNumbers(9, 81)); // 90 function addTwoNumbersWithCallback(first, second, handler) { var sum = (first + second); handler(sum); } function handleResult(result) { window.alert(result); } addTwoNumbersWithCallback(9, 81, handleResult); EduVault/eduvault const isProdEnv = () => process.env.NODE_ENV === 'production' export const PROD_HOST = process.env.VUE_APP_PROD_HOST || 'eduvault-staging.click' const HOST = isProdEnv() ? PROD_HOST : 'localhost' export const EDUVAULT_APP_URL = 'http://app.' + HOST export const EXAMPLE_APP_URL = 'http://example.' + HOST 10-100 var pkg = require('./package.json') var babel = require('babel-core') module.exports = function (wallaby) { var config = pkg.babel config.babel = babel return { files: ['index.js', 'lib/*', 'package.json', 'test/config.js', 'test/support/helpers.js'], tests: ['test/index.js'], env: { type: 'node', runner: 'node' }, testFramework: 'mocha@2.1.0', // debug: true, compilers: { '**/*.js': wallaby.compilers.babel(config) }, bootstrap: function (w) { require('./test/support/helpers') w.testFramework.timeout(10000) console.log(w.testFramework) } } } var searchData= [ ['expxs_2ef90',['expxs.f90',['../expxs_8f90.html',1,'']]] ]; const EthereumBlockchain = require('../lib/blockchains/EthereumBlockchain').EthereumBlockchain const BigNumber = require('bignumber.js') describe("EthereumBlockchain check for eth balance", () => { test('return balance as a BigNumber object', async () => { const ethBlockchain = new EthereumBlockchain({ infuraProjectId: "39f6ad316c5a4b87a0f90956333c3666", blockchainNetwork: 'ethereum_ropsten' }) jest.spyOn(ethBlockchain, "connect").mockImplementation(() => { return true }); jest.spyOn(ethBlockchain.chain, "fetchBalance").mockImplementation(() => { return { balance: "99.5" } }); const balance = await ethBlockchain.getEthBalance("0x2aA78Db0BEff941883C33EA150ed86eaDE09A377") expect(balance).toEqual(new BigNumber("99.5")) }) test('return zero of something went wrong', async () => { const ethBlockchain = new EthereumBlockchain({ infuraProjectId: "39f6ad316c5a4b87a0f90956333c3666", blockchainNetwork: 'ethereum_ropsten' }) jest.spyOn(ethBlockchain, "connect").mockImplementation(() => { return true }); jest.spyOn(ethBlockchain.chain, "fetchBalance").mockImplementation(() => { return { something: "wrong" } }); const balance = await ethBlockchain.getEthBalance("0x2aA78Db0BEff941883C33EA150ed86eaDE09A377") expect(balance).toEqual(new BigNumber(0)) }) }); angular.module('emailController',['userService']) // Activating user account through email link .controller('emailCtrl', function($stateParams, userFactory, $location, $state){ app = this; // Check function that grabs token from URL and checks database runs on page load this.activate = function(){ userFactory.activateaccount($stateParams.token).then(function(data) { // Check if activation was successful or not if (data.data.success) { app.successMsg = data.data.message + '...Redirecting'; // If successful, grab message from JSON object and redirect to login page $state.go('app.login'); } else { app.errorMsg = data.data.message + '...Redirecting'; // If not successful, grab message from JSON object and redirect to login page } }); } // Similar function to reset password this.resetpassword = function(resetData, valid){ console.log(resetData) if(!valid) { app.loading = false; app.errorMsg += "\nPlease make sure the form is complete and all fields are valid before submitting..."; } else { userFactory.resetpassword($stateParams.token, resetData).then(function(data) { console.log($stateParams.token) // Check if activation was successful or not if (data.data.success) { app.successMsg = data.data.message + 'Success!...Redirecting'; // If successful, grab message from JSON object and redirect to login page $state.go('app.login') } else { app.errorMsg = data.data.message + 'Failed!...Redirecting'; // If not successful, grab message from JSON object and redirect to login page // $state.go('app.login') } }); } } }) .directive('resetMatchPw', [function () { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { var firstPassword = resetForm.password; $(elem).add(firstPassword).on('keyup', function () { scope.$apply(function () { var v = elem.val()===$(firstPassword).val(); ctrl.$setValidity('pwmatch', v); }); }); } } }]) archSeer/vue-react-dnd import Vue from 'vue' import VueRouter from 'vue-router' import App from './App' import {routes} from './routes' const debug = process.env.NODE_ENV !== 'production' Vue.use(VueRouter) export const router = new VueRouter({ mode: debug ? 'hash' : 'history', base: debug ? '/' : 'vue-react-dnd', routes: routes }) /* eslint-disable no-new */ new Vue({ el: '#app', components: { App }, render: mount => mount(App), router }) /* eslint-disable no-undef */ let envObject = { branch: "master" }; if (process.env.NODE_ENV === "development") { envObject.name = "proxy"; envObject.proxy_url = "http://localhost:8081/api/v1"; } else if (process.env.NODE_ENV === "production") { envObject.name = "git-gateway"; } export default envObject; console.log("The environment is:", process.env.NODE_ENV, envObject);const Card = require('../../Card.js'); class CutthroatResearch extends Card { setupCardAbilities(ability) { this.play({ condition: context => context.player.opponent && context.player.opponent.amber >= 8, gameAction: ability.actions.steal({ amount: 2 }) }); } } CutthroatResearch.id = 'cutthroat-research'; module.exports = CutthroatResearch; var $body = document.body; var $toggle = document.querySelector(".navbar-toggle"); var $navbar = document.querySelector("#Quanyinblog_navbar"); var $collapse = document.querySelector(".navbar-collapse"); var __QuanyinNav__ = { close: function close() { $navbar.className = " "; setTimeout(function () { if ($navbar.className.indexOf("in") < 0) { $collapse.style.height = "0px"; } }, 400); }, open: function open() { $collapse.style.height = "auto"; $navbar.className += " in"; } }; $toggle.addEventListener("click", function (e) { if ($navbar.className.indexOf("in") > 0) { __QuanyinNav__.close(); } else { __QuanyinNav__.open(); } }); document.addEventListener("click", function (e) { if (e.target == $toggle) return; if (e.target.className == "icon-bar") return; __QuanyinNav__.close(); }); /** * SnackBar.js * * This small component is borrowed from * https://codepen.io/wibblymat/pen/avAjq */ var createSnackbar = function () { // Any snackbar that is already shown var previous = null; /*
This is a longer message that won't fit on one line. It is, inevitably, quite a boring thing. Hopefully it is still useful.
*/ return function (config) { var message = config.message, actionText = config.actionText, action = config.action, duration = config.duration; if (previous) { previous.dismiss(); } var snackbar = document.createElement('div'); snackbar.className = 'paper-snackbar'; snackbar.dismiss = function () { this.style.opacity = 0; }; var text = document.createTextNode(message); snackbar.appendChild(text); if (actionText) { if (!action) { action = snackbar.dismiss.bind(snackbar); } var actionButton = document.createElement('button'); actionButton.className = 'action'; actionButton.innerHTML = actionText; actionButton.addEventListener('click', action); snackbar.appendChild(actionButton); } setTimeout(function () { if (previous === this) { previous.dismiss(); } }.bind(snackbar), duration || 5000); snackbar.addEventListener('transitionend', function (event, elapsed) { if (event.propertyName === 'opacity' && this.style.opacity == 0) { this.parentElement.removeChild(this); if (previous === this) { previous = null; } } }.bind(snackbar)); previous = snackbar; document.body.appendChild(snackbar); // In order for the animations to trigger, I have to force the original style to be computed, and then change it. getComputedStyle(snackbar).bottom; snackbar.style.bottom = '0px'; snackbar.style.opacity = 1; }; }(); /* =========================================================== * sw-registration.js * =========================================================== * Copyright 2017 @Quanyin * Licensed under Apache 2.0 * Register service worker. * ========================================================== */ /* SW Version Upgrade Ref: */ function handleRegistration(registration) { console.log('Service Worker Registered. ', registration); /** * ServiceWorkerRegistration.onupdatefound * The service worker registration's installing worker changes. */ registration.onupdatefound = function (e) { var installingWorker = registration.installing; installingWorker.onstatechange = function (e) { if (installingWorker.state !== 'installed') return; if (navigator.serviceWorker.controller) { console.log('SW is updated'); } else { console.log('A Visit without previous SW'); createSnackbar({ message: 'App ready for offline use.', duration: 3000 }); } }; }; } if (navigator.serviceWorker) { /* For security reasons, a service worker can only control the pages */ /* that are in the same directory level or below it. That's why we put sw.js at ROOT level. */ navigator.serviceWorker.register('/sw.min.js').then(function (registration) { return handleRegistration(registration); }).catch(function (error) { console.log('ServiceWorker registration failed: ', error); }); /* register message receiver */ /* https://dbwriteups.wordpress.com/2015/11/16/service-workers-part-3-communication-between-sw-and-pages/ */ navigator.serviceWorker.onmessage = function (e) { console.log('SW: SW Broadcasting:', event); var data = e.data; if (data.command == "UPDATE_FOUND") { console.log("UPDATE_FOUND_BY_SW", data); createSnackbar({ message: "Content updated.", actionText: "refresh", action: function action(e) { location.reload(); } }); } }; } var bszCaller, bszTag;!function () { var c, d, _e, a = !1, b = [];ready = function ready(c) { return a || "interactive" === document.readyState || "complete" === document.readyState ? c.call(document) : b.push(function () { return c.call(this); }), this; }, d = function d() { for (var a = 0, c = b.length; c > a; a++) { b[a].apply(document); }b = []; }, _e = function e() { a || (a = !0, d.call(window), document.removeEventListener ? document.removeEventListener("DOMContentLoaded", _e, !1) : document.attachEvent && (document.detachEvent("onreadystatechange", _e), window == window.top && (clearInterval(c), c = null))); }, document.addEventListener ? document.addEventListener("DOMContentLoaded", _e, !1) : document.attachEvent && (document.attachEvent("onreadystatechange", function () { /loaded|complete/.test(document.readyState) && _e(); }), window == window.top && (c = setInterval(function () { try { a || document.documentElement.doScroll("left"); } catch (b) { return; }_e(); }, 5))); }(), bszCaller = { fetch: function fetch(a, b) { var c = "BusuanziCallback_" + Math.floor(1099511627776 * Math.random());window[c] = this.evalCall(b), a = a.replace("=BusuanziCallback", "=" + c), scriptTag = document.createElement("SCRIPT"), scriptTag.type = "text/javascript", scriptTag.defer = !0, scriptTag.src = a, document.getElementsByTagName("HEAD")[0].appendChild(scriptTag); }, evalCall: function evalCall(a) { return function (b) { ready(function () { try { a(b), scriptTag.parentElement.removeChild(scriptTag); } catch (c) { bszTag.hides(); } }); }; } }, bszCaller.fetch("//busuanzi.ibruce.info/busuanzi?jsonpCallback=BusuanziCallback", function (a) { bszTag.texts(a), bszTag.shows(); }), bszTag = { bszs: ["site_pv", "page_pv", "site_uv"], texts: function texts(a) { this.bszs.map(function (b) { var c = document.getElementById("busuanzi_value_" + b);c && (c.innerHTML = a[b]); }); }, hides: function hides() { this.bszs.map(function (a) { var b = document.getElementById("busuanzi_container_" + a);b && (b.style.display = "none"); }); }, shows: function shows() { this.bszs.map(function (a) { var b = document.getElementById("busuanzi_container_" + a);b && (b.style.display = "inline"); }); } }; /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */ /* This file is meant as a standalone workflow for - testing support for link[rel=preload] - enabling async CSS loading in browsers that do not support rel=preload - applying rel preload css once loaded, whether supported or not. */ (function( w ){ "use strict"; // rel=preload support test if( !w.loadCSS ){ w.loadCSS = function(){}; } // define on the loadCSS obj var rp = loadCSS.relpreload = {}; // rel=preload feature support test // runs once and returns a function for compat purposes rp.support = (function(){ var ret; try { ret = w.document.createElement( "link" ).relList.supports( "preload" ); } catch (e) { ret = false; } return function(){ return ret; }; })(); // if preload isn't supported, get an asynchronous load by using a non-matching media attribute // then change that media back to its intended value on load rp.bindMediaToggle = function( link ){ // remember existing media attr for ultimate state, or default to 'all' var finalMedia = link.media || "all"; function enableStylesheet(){ link.media = finalMedia; } // bind load handlers to enable media if( link.addEventListener ){ link.addEventListener( "load", enableStylesheet ); } else if( link.attachEvent ){ link.attachEvent( "onload", enableStylesheet ); } // Set rel and non-applicable media type to start an async request // note: timeout allows this to happen async to let rendering continue in IE setTimeout(function(){ link.rel = "stylesheet"; link.media = "only x"; }); // also enable media after 3 seconds, // which will catch very old browsers (android 2.x, old firefox) that don't support onload on link setTimeout( enableStylesheet, 3000 ); }; // loop through link elements in DOM rp.poly = function(){ // double check this to prevent external calls from running if( rp.support() ){ return; } var links = w.document.getElementsByTagName( "link" ); for( var i = 0; i < links.length; i++ ){ var link = links[ i ]; // qualify links to those with rel=preload and as=style attrs if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){ // prevent rerunning on link link.setAttribute( "data-loadcss", true ); // bind listeners to toggle media back rp.bindMediaToggle( link ); } } }; // if unsupported, run the polyfill if( !rp.support() ){ // run once at least rp.poly(); // rerun poly on an interval until onload var run = w.setInterval( rp.poly, 500 ); if( w.addEventListener ){ w.addEventListener( "load", function(){ rp.poly(); w.clearInterval( run ); } ); } else if( w.attachEvent ){ w.attachEvent( "onload", function(){ rp.poly(); w.clearInterval( run ); } ); } } // commonjs if( typeof exports !== "undefined" ){ exports.loadCSS = loadCSS; } else { w.loadCSS = loadCSS; } }( typeof global !== "undefined" ? global : this ) ); window.onscroll = function () { var goTop = document.getElementsByClassName("back2top"); if (goTop.length > 0) { goTop[0].style.display = document.documentElement.scrollTop >= 300 || document.body.scrollTop >= 300 ? 'block' : 'none'; goTop[0].onclick = function () { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; }; } };'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Filter = require('./Filter'); var _Filter2 = _interopRequireDefault(_Filter); var _utils = require('./utils'); var _yup = require('yup'); var yup = _interopRequireWildcard(_yup); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var schema = yup.object({ client: yup.mixed().required(), contracts: yup.array().of(yup.string().max(42).matches(/^0x/)).required(), filter: _Filter.filterSchema.clone().required(), groupBy: yup.string().max(50), timeRange: yup.object({ start: yup.number().positive().integer(), end: yup.number().positive().integer() }), limit: yup.number().positive().integer(), offset: yup.number().moreThan(-1).integer(), count: yup.boolean() }); /** * Query class. This is created by the BHubClient but is also possible * to create directly. */ var Query = function () { function Query(props) { var _this = this; _classCallCheck(this, Query); schema.validateSync(props); this.client = props.client; this.contracts = props.contracts; this.filter = props.filter; //all extra fields this.groupBy = props.groupBy; this.limit = props.limit || 10; this.offset = props.offset || 0; this.count = props.count; this.timeRange = props.timeRange; if (props.timeRange && props.timeRange.start > props.timeRange.end) { (0, _utils._throw)("Query", "range start must be before range end"); } ['execute'].forEach(function (fn) { _this[fn] = _this[fn].bind(_this); }); } /** * Execute the query (async). */ _createClass(Query, [{ key: 'execute', value: function execute() { schema.validateSync(this); return this.client._runQuery(this); } }]); return Query; }(); exports.default = Query;import React, { Component } from 'react' import { Link } from 'react-router-dom' import home from './../../assets/home.jpg' export default class Landing extends Component { render() { return (

We transform the

Agriculture world


We help increase crop production by providing
affordable and actionable information to a range of
actors, most imporantly smallholder farmers


More
) } }/** * Patterns carousel * * Copyright 2017 Syslab.com GmbH */ define([ "jquery", "pat-registry", "pat-logger", "pat-parser", "slick-carousel" ], function($, patterns, logger, Parser) { var log = logger.getLogger("pat.carousel"), parser = new Parser("carousel"); parser.addArgument("auto-play", false); parser.addArgument("auto-play-speed", 1000); parser.addArgument("speed", 500); parser.addArgument("height", "fixed"); parser.addArgument("arrows", "show"); parser.addArgument("slides-to-show", 1); parser.addArgument("slides-to-scroll", 1); parser.addArgument("dots", "show"); parser.addArgument("append-dots", ""); parser.addArgument("infinite", false); var carousel = { name: "carousel", trigger: ".pat-carousel", init: function($el, opts) { return $el.each(function() { var $carousel = $(this), options = parser.parse($carousel, opts), settings = {}; settings.autoplay = options.auto.play; settings.autoplaySpeed = options.auto['play-speed']; settings.speed = options.speed; settings.adaptiveHeight = options.height === "adaptive"; settings.arrows = options.arrows === "show"; settings.slidesToShow = options.slides["to-show"]; settings.slidesToScroll = options.slides["to-scroll"]; settings.dots = options.dots === "show"; if (options.appendDots) { settings.appendDots = options.appendDots; } settings.infinite = options.infinite; carousel.setup($carousel, settings); }); }, setup: function($el, settings) { var loaded = true, $images = $el.find("img"), img, i; for (i=0; loaded && i<$images.length; i++) { img=$images[i]; if (!img.complete || img.naturalWidth===0) loaded=false; } if (!loaded) { log.debug("Delaying carousel setup until images have loaded."); setTimeout(function() { carousel.setup($el, settings); }, 50); return; } var $carousel = $el.slick(settings), // control = $carousel.data("AnythingSlider"), $panel_links = $(); $carousel .children().each(function(index) { if (!this.id) return; var $links = $("a[href=#" + this.id+"]"); if (index===control.currentPage) $links.addClass("current"); else $links.removeClass("current"); $links.on("click.pat-carousel", null, {control: control, index: index}, carousel.onPanelLinkClick); $panel_links = $panel_links.add($links); }).end() .on("slide_complete.pat-carousel", null, $panel_links, carousel.onSlideComplete); }, _loadPanelImages: function(slider, page) { var $img; log.info("Loading lazy images on panel " + page); slider.$items.eq(page).find("img").addBack().filter("[data-src]").each(function() { $img=$(this); this.src=$img.attr("data-src"); $img.removeAttr("data-src"); }); }, onPanelLinkClick: function(event) { event.data.control.gotoPage(event.data.index, false); event.preventDefault(); }, onInitialized: function(event, slider) { carousel._loadPanelImages(slider, slider.options.startPanel); carousel._loadPanelImages(slider, slider.options.startPanel+1); carousel._loadPanelImages(slider, 0); carousel._loadPanelImages(slider, slider.pages+1); }, onSlideInit: function(event, slider) { carousel._loadPanelImages(slider, slider.targetPage); }, onSlideComplete: function(event, slider) { var $panel_links = event.data; $panel_links.removeClass("current"); if (slider.$targetPage[0].id) $panel_links.filter("[href=#" + slider.$targetPage[0].id + "]").addClass("current"); carousel._loadPanelImages(slider, slider.targetPage+1); } }; patterns.register(carousel); return carousel; // XXX For testing only }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab // app.js (function($, window, document) { function initIziModalEventHandlers() { $('[data-modal-open]').on('click', function(e){ e.preventDefault(); var modalID = $(this).data('modal-open'); $('#' + modalID).iziModal('open'); }); } function initIziModals() { $('[data-modal]').iziModal({ history: false, transitionIn: 'fadeInUp', transitionOut: 'fadeOutDown', transitionInOverlay: 'fadeIn', transitionOutOverlay: 'fadeOuts', width: '1347px' }); } function initializePOI() { //open interest point description $('.cd-single-point').children('a').on('click', function(e){ e.preventDefault(); var selectedPoint = $(this).parent('li'); if(selectedPoint.hasClass('is-open')) { selectedPoint.removeClass('is-open').addClass('visited'); } else { selectedPoint.addClass('is-open').siblings('.cd-single-point.is-open').removeClass('is-open').addClass('visited'); } }); //close interest point description $('.cd-close-info').on('click', function(event){ event.preventDefault(); $(this).parents('.cd-single-point').eq(0).removeClass('is-open').addClass('visited'); }); } //Initalize functions for page load initIziModalEventHandlers(); initIziModals(); initializePOI(); }(window.jQuery, window, document));import React, { Component } from "react"; import { Badge, Button, Card, CardBody, CardHeader, Col, ListGroup, ListGroupItem, ListGroupItemHeading, ListGroupItemText, Row, TabContent, TabPane, Input } from "reactstrap"; import LoadingOverlay from "react-loading-overlay"; import { getAllUsersAdmin } from "../../../ApiCalls/user"; import UserService from "../../../services/User"; import validateInput from "../../../validation/input"; import { getCompanyDrivers } from "../../../ApiCalls/driver"; import DangerModal from "../../CustomModals/DangerModal"; import SuccessModal from "../../CustomModals/SuccessModal"; import UserDetailsModal from "../../CustomModals/UserDetailsModal"; export default class ShowUsersAdmin extends Component { constructor(props) { super(props); this.state = { users: [], isErrorModalVisible: false, modalErrorMessage: "", isSuccessModalVisible: false, successModalTitle: "Sucessful", modalSuccessMessage: "", isLoadDetailsModalVisible: false, userDetails: {}, drivers : [], userId: "", user:{}, loading:false, companyStatus:0, }; this.userService = new UserService(); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.toggleDangerModal = this.toggleDangerModal.bind(this); this.toggleSuccessModal = this.toggleSuccessModal.bind(this); this.toggleLoadDetaildModal = this.toggleLoadDetaildModal.bind(this); this.loadUserOrRedirect = this.loadUserOrRedirect.bind(this); this.loadAllUsers = this.loadAllUsers.bind(this); this.loadCompanyDrivers = this.loadCompanyDrivers.bind(this); } componentWillMount() { this.loadUserOrRedirect(); this.loadAllUsers(); } async loadAllUsers() { this.setState({loading:true}); try{ const promise = await getAllUsersAdmin(this.state.companyStatus); console.log("user data",promise); const data = promise.data.data; this.setState({ users: data }); } catch (err) { const response = err.response; console.log(err.response); if (response && response.status === 401) { const errorMessage = "Session expired, please login to continue"; alert(errorMessage); this.userService.clearData(); this.props.history.push("/login"); } } this.setState({loading:false}); } async loadCompanyDrivers(id) { console.log("id",id); this.setState({loading:true}); try{ const promise = await getCompanyDrivers(id); const data = promise.data.data; console.log("driver data",promise.data); this.setState({drivers:data,loading:false}); } catch (err) { const response = err.response; console.log(err.response); if (response && response.status === 401) { const errorMessage = "Session expired, please login to continue"; alert(errorMessage); this.userService.clearData(); this.props.history.push("/login"); } } } async loadUserOrRedirect() { const user = await this.userService.getUser(); if (!user) { this.props.history.push("/login"); } } toggleDangerModal() { this.setState((state, props) => ({ isErrorModalVisible: !state.isErrorModalVisible })); } toggleLoadDetaildModal() { this.setState((state, props) => ({ isLoadDetailsModalVisible: !state.isLoadDetailsModalVisible })); } toggleSuccessModal() { this.setState((state, props) => ({ isSuccessModalVisible: !state.isSuccessModalVisible })); } handleChange(e) { this.setState({ [e.target.name]: e.target.value }); } async handleSubmit(e) { e.preventDefault(); } render() { return (
({ ...base, width: "250px", background: "rgba(0, 0, 0, 0.2)" }) }} spinner text="" />

Select status


Pending Companies {/* custom content */} {this.state.users.map(user => { return ( {user.name} {/*
*/} Phone : {user.phone} Email : {user.email} MC# : {user.MC} DOT# : {user.DOT} ); })}
); } } 1-10 //Dependencies var User = require('User'), ui = require('ui'); //App configuration Ti.Facebook.appid = Ti.App.Properties.getString('ti.facebook.appid'); Ti.Facebook.permissions = ['publish_stream']; //TODO: Be more tolerant of offline if (!Ti.Network.online) { ui.alert('networkErrTitle', 'networkErrMsg'); } //create view hierarchy components $.login = Alloy.createController('login'); //Check Login Status if (User.confirmLogin()) { $.main = Alloy.createController('main'); $.clouds && ($.index.remove($.clouds)); $.index.backgroundImage = '/img/general/bg-interior.png'; $.index.add($.main.getView()); $.main.init(); } else { $.index.backgroundImage = '/img/general/bg-cloud.png'; $.index.add($.login.getView()); $.login.init(); } //Monitor Login Status $.login.on('loginSuccess', function(e) { $.main = Alloy.createController('main'); $.clouds && ($.index.remove($.clouds)); $.index.backgroundImage = '/img/general/bg-interior.png'; $.index.add($.main.getView()); ui.zoom($.login.getView(), function() { ui.unzoom($.main.getView(), function() { $.main.init(); }); }); }); //Look for global logout event Ti.App.addEventListener('app:logout', function(e) { $.clouds && ($.index.add($.clouds)); $.index.backgroundImage = '/img/general/bg-cloud.png'; $.index.add($.login.getView()); $.login.init(); ui.zoom($.main.getView(), function() { ui.unzoom($.login.getView()); }); }); //Lock orientation modes for handheld if (!Alloy.isTablet) { $.index.orientationModes = [ Ti.UI.PORTRAIT, Ti.UI.UPSIDE_PORTRAIT ]; } //TODO: At some point, a better UX would be to close open drawers until there are none, and then exit if (Ti.Platform.osname === 'android') { $.index.addEventListener('android:back', function() { var od = Ti.UI.createOptionDialog({ title:L('leave'), options:[L('ok'), L('cancel')], cancel:1 }); od.addEventListener('click', function(e) { e.index === 0 && ($.index.close()); }); od.show(); }); } //Open initial window $.index.open(); const CustomError = require("../../helpers/error/CustomError") //Error Handler const customErrorHandler = (err, req, res, next) => { let customError = err; // console.log(err.name) if (err.name === "SyntaxError") { customError = new CustomError("Beklenmedik Kod Hatası", 400) } if (err.name === "ValidationError") { customError = new CustomError(err.message, 400) } if (err.name === "CastError") { customError = new CustomError("Lütfen Geçerli Bir ID Giriniz", 400) } if (err.code === 11000) { customError = new CustomError("Lütfen Farklı bir e-posta girin.", 400) } console.log(customError.name, customError.message, customError.status) res.status(customError.status || 500).json({ success: false, message: customError.message || "Dahili Sunucu Hatası" }) } module.exports = customErrorHandler; /* eslint-env jest */ import rasterize, { PALETTE_SIZE } from '../src/palette'; describe('rasterize', () => { it('creates smooth two-color palette', () => { const palette = [[0, 0, 0, 255], [255, 255, 255, 255]]; const colors = rasterize(palette); expect(colors).toHaveLength(PALETTE_SIZE); expect(colors.every(({ 3: alpha }) => alpha === 255)).toBe(true); colors.forEach(({ 0: r, 1: g, 2: b }, i) => { expect(r).toBe(i); expect(g).toBe(i); expect(b).toBe(i); }); }); it('creates smooth three-color palette', () => { const palette = [[0, 0, 0, 255], [255, 0, 0, 255], [0, 0, 255, 255]]; const colors = rasterize(palette); expect(colors).toHaveLength(PALETTE_SIZE); expect(colors.every(({ 3: alpha }) => alpha === 255)).toBe(true); colors.slice(0, 128).forEach(({ 0: r, 1: g, 2: b }, i) => { expect(r).toBe(2 * i); expect(g).toBe(0); expect(b).toBe(0); }); colors.slice(127).forEach(({ 0: r, 1: g, 2: b }, i) => { expect(Math.abs(r - 255 + 2 * i)).toBeLessThan(2); expect(g).toBe(0); expect(Math.abs(b - 2 * i)).toBeLessThan(2); }); }); it('works with named palette', () => { const palette = [[0, 0, 0], [187, 187, 187], [255, 255, 255]]; const colors = rasterize(palette); expect(rasterize('grayscale')).toEqual(colors); }); it('throws an error or unknown named palette', () => { expect(() => rasterize('dont-know-lol')).toThrow(/unknown/i); }); }); tksugimoto/chrome-extension_assist-video-controller Promise.resolve(document.getElementsByTagName('video')).then(videos => { const targetVideoSrc = window.targetVideoSrc; if (typeof targetVideoSrc !== 'undefined') { const targetVideos = Array.from(videos).filter(video => { if (video.src === targetVideoSrc) return true; return Array.from(video.getElementsByTagName('source')).find(source => { return source.src === targetVideoSrc; }); }); return {videos, targetVideos}; } else { return {videos, targetVideos: videos}; } }).then(({videos, targetVideos}) => { if (targetVideos.length === 1) return {videos, targetVideo: targetVideos[0]}; if (targetVideos.length === 0) throw '対象
); } export default AdminRegistration; let nome = ''; let resultado = nome.substr(-5, 5); console.log(resultado); /* Função de string apresentadas: "nome.slice(0, 10 ...)" - Retorna correspondente ao valor que colocar. Pode ser usado número negativo, porém ela vai pegar do fim para início. "nome.substring(0, 10)"" - Retorna correspondente ao valor que colocar. Não funciona com número negativo. "nome.substr(0, 10)" - O primeiro número será a posição inicial. O segundo número a quantida de caracteres que você que que ele busque. E ele funciona com negativos também. ;) 90% das vezes o "substr" vai te atender. */sheeshmohsin/waartaaapp/client/subscribe.js /* Data subscription code. */ function subscribeToLatestChatroomLog () { var _subscriptions = { 'channels': {}, 'servers': {}, 'pms': {} }; var subs = new SubsManager({ cacheLimit: 1000, expireIn: 9999 }); UserChannels.find().observeChanges({ added: function (id, channel) { var loadTime = new Date(); _subscriptions['channels'][id] = subs.subscribe( 'latest_channel_log', channel.user_server_name, channel.name); localChatRoomLogCount.reset(channel.user_server_name + '::' + channel.name); ChannelLogs.find( { server_name: channel.user_server_name, channel_name: channel.name, created: {$gt: loadTime}, global: true } ).observeChanges({ added: function (id, fields) { if (fields.type != 'ChannelJoin' && fields.type != 'ChannelPart' && fields.type != 'QUITIRC') { localChatRoomLogCount.increment( channel.user_server_name + '::' + channel.name); } var currentRouter = Router.current(); var userServer = UserServers.findOne({ name: channel.user_server_name}); // Alert user on mention on unfocussed chat room if ( userServer && (fields.created > loadTime || !window_focus) && fields.from && messageContainsNick(fields.message, userServer.current_nick) && ( !( currentRouter.params.serverName == userServer.name && '#' + currentRouter.params.channelName == channel.name ) || !window_focus ) ) { var alert_message = fields.server_name + fields.channel_name + ': ' + fields.message; $.titleAlert(alert_message, { requireBlur:true, stopOnFocus:true, duration:10000, interval:500 }); $('#audio-notification')[0].play(); } } }); }, removed: function (id) { if (_subscriptions['channels'][id]) delete _subscriptions['channels'][id]; } }); UserPms.find().observeChanges({ added: function (id, pm) { var loadTime = new Date(); _subscriptions['pms'][id] = subs.subscribe( 'latest_pm_log', pm.user_server_name, pm.name); localChatRoomLogCount.reset( pm.user + '||' + pm.user_server_name + '::' + pm.name); PMLogs.find( { server_name: pm.user_server_name, from: pm.name, created: {$gt: loadTime} } ).observeChanges({ added: function (id, fields) { var currentRouter = Router.current(); var userServer = UserServers.findOne({ name: pm.user_server_name}) || {}; localChatRoomLogCount.increment( pm.user + '||' + pm.user_server_name + '::' + pm.name); if ( (fields.created > loadTime || !window_focus) && ( !(currentRouter.params.serverName == pm.user_server_name && currentRouter.params.nick == pm.name) || !window_focus ) ) { var alert_message = pm.name + ' messaged you: ' + fields.message; $.titleAlert(alert_message, { requireBlur:true, stopOnFocus:true, duration:10000, interval:500 }); $('#audio-notification')[0].play(); } } }); }, removed: function (id) { if (_subscriptions['channels'][id]) delete _subscriptions['pms'][id]; } }); UserServers.find().observeChanges({ added: function (id, server) { var loadTime = new Date(); var user = Meteor.user(); if (!user) return; _subscriptions['servers'][id] = subs.subscribe( 'latest_server_log', server.name); localChatRoomLogCount.reset(user.username + '||' + server.name); UserServerLogs.find( { server_name: server.name, created: {$gt: loadTime} } ).observeChanges({ added: function (id, fields) { localChatRoomLogCount.increment( user.username + '||' + server.name); } }); }, removed: function (id) { if (_subscriptions['servers'][id]) delete _subscriptions['servers'][id]; } }); } Meteor.startup(function () { subscribeToLatestChatroomLog(); }); /* globals i18n */ var fhreq = require("../../utils/request"); var common = require("../../common.js"); var log = require("../../utils/log"); var fhc = require("../../fhc"); var async = require('async'); var http = require("http"); var https = require("https"); var url = require("url"); var fs = require("fs"); var _ = require("underscore"); var qrcode = require("qrcode-terminal"); const DEPRECATION_NOTICE = "The fhc build command is DEPRECATED. For more details, please see https://redhatmobilestatus.com/2018/09/26/immediate-deprecation-of-the-rhmap-client-binary-build-service-build-farm/. "; module.exports = { 'desc' : i18n._('[DEPRECATED] Builds a client application'), 'deprecation': i18n._(DEPRECATION_NOTICE), 'examples' : [{ cmd : '[DEPRECATED] fhc build --project= --app= --cloud_app= --tag= --environment= --destination= --version= --config= --privateKeyPass= --certpass= --download= --bundleId= --cordova_version= --git-tag= --git-branch= --git-commit=', desc : "[DEPRECATED] Build a client of the connect to the deployed into the " }], 'demand' : ['project','app','cloud_app','destination','environment'], 'alias' : { 'project': 'p', 'app': 'a', 'cloud_app': 'ca', 'tag': 't', 'environment': 'e', 'destination': 'd', 'version': 'v', 'config': 'c', 'privateKeyPass': 'pk', 'certpass': 'cp', 'download': 'dw', 'bundleId': 'b', 'cordova_version': 'cv', 'git-tag': 'gt', 'git-branch': 'gb', 'git-commit': 'gc', 'json' : 'j', 0: 'project', 1: 'app', 2: 'cloud_app', 3: 'destination', 4: 'environment' }, 'describe' : { 'project' : i18n._("Unique 24 character GUID of the project."), 'app' : i18n._("Unique 24 character GUID of the client app which will be built."), 'cloud_app' : i18n._("Unique 24 character GUID of the cloud app which the client app will connect to."), 'tag' : i18n._("The name of a connection tag for the cloud app, must be in Semantic Version format, e.g. 0.0.1. See: http://semver.org."), 'environment' : i18n._("The id of a target environment, e.g. dev."), 'destination' : i18n._("One of: android, iphone, ipad, ios(for universal binary)"), 'version' : i18n._("Specific to the destination (e.g. Android version 4.0)."), 'config' : i18n._("Either 'debug' (default), 'distribution', or 'release'."), 'privateKeyPass' : i18n._("Private key password of the bundleId, only needed for 'release' builds."), 'certpass' : i18n._("Certificate password."), 'download' : i18n._("Boolean value to inform to download or not the built when it finish."), 'bundleId' : i18n._("The unique bundle identifier of the credential bundle. You can get it using 'fhc credentials list'. Required for all iOS builds."), 'cordova_version' : i18n._("For specifying which version of Cordova to use. Currently supported: either 2.2 or 3.3. Only valid for Android for now."), 'git-tag' : i18n._("Long value of URL that you want shorter for the henr.ie URL."), 'git-branch' : i18n._("The name of the git branch to build, defaults to 'master'."), 'git-commit' : i18n._("The full hash of the commit to build, if not the head of the branch. Must be used with ."), 'json' : i18n._('Output into json format') }, 'preCmd' : function(params,cb) { if (!params.config) { params.config = 'debug'; } else if (params.config === 'release' || params.config === 'distribution') { if (!params.privateKeyPass) { return cb(i18n._("Missing 'privateKeyPass' parameter")); } if (!params.certpass) { return cb(i18n._("Missing 'certpass' parameter")); } } if (isIosBuild(params)) { params.deviceType = params.destination; if (!params.bundleId) { return cb(i18n._("Missing 'bundleId' parameter")); } } // set default build version if none specified. Note this is hardcoded as not available from millicore API. // note these values were gotten from studio/static/js/application/destinations/destination_* if (!params.version) { if (params.destination === 'android') { params.version = '4.0'; } else if (isIosBuild(params)) { params.version = '6.0'; } } params.generateSrc=false; return cb(null, params); }, 'customCmd' : function(params,cb) { try { mutateGitRefArgs(params); doBuild(params, cb); } catch (x) { log.silly(x); return cb(i18n._("Error processing params: ") + x + "\n"); } } }; /** * Check if the destination is iphone, ipad or ios * @param params * @returns {boolean} */ function isIosBuild(params) { return params.destination === "iphone" || params.destination === "ipad" || params.destination === "ios"; } /** * Mutates the arguments object in order to support --git-branch --git-commit and --git-tag, turning them into gitRef * @param {Object} params Arguments object */ function mutateGitRefArgs(params) { // Workaround for current millicore behavior: // If no git- params are present, build from branch:master var gitParams = [ 'git-commit', 'git-tag', 'git-branch' ]; if (!_.any(gitParams, _.propertyOf(params))) { params.gitRef = { type: 'branch', value: 'master' }; return; } function clearGitParams(params) { _.each(gitParams, function(p) { delete params[p]; }); } // priority is commit > tag > branch if (params['git-commit']) { params.gitRef = { type: 'commit', value: params['git-commit'], hash: params['git-commit'] }; clearGitParams(params); return; } if (params['git-tag']) { params.gitRef = { type: 'tag', value: params['git-tag'] }; clearGitParams(params); return; } if (params['git-branch']) { params.gitRef = { type: 'branch', value: params['git-branch'] }; clearGitParams(params); return; } } /** * To create the URL to perform the build * @param params * @returns {string} */ function createUri(params) { return "box/srv/1.1/wid/" + fhc.curTarget + "/" + params.destination + "/" + params.app + "/deliver"; } function createMessageWithOtaUrl(message, buildResults) { message = message + i18n._("\nOTA URL: ") + buildResults.ota_url; qrcode.generate(buildResults.ota_url, {small: true}, function(code) { message = message + "\n" + code; }); return message; } /** * Download the artefact built into the local directory * @param params * @param build_asset * @param cb * @param buildResults * @param message */ function doDownload(params, build_asset, cb, buildResults, message) { downloadBuild(params, build_asset, './', function(err, data) { if (err) { return cb(err); } if (data) { buildResults.download = data; message = message + i18n._("\nDownloaded file: ") + data.file; } return cb(null, message); }); } /** * Create and print the console message * @param message * @param buildResults * @param params * @param cb */ function doConsoleMessage(message, buildResults, params, cb) { message = i18n._("\nDownload URL: ") + buildResults.url; if (buildResults.ota_url) { message = createMessageWithOtaUrl(message, buildResults); } doDownload(params, buildResults.url, cb, buildResults, message); } /** * Get the data returned and perform the success outcome * @param results * @param cb * @param params */ function doSuccessOutcome(results, cb, params) { var message = ""; var artifactUrls = results[0][0].action; getArtifactUrl(artifactUrls, function(err, buildResults) { if (err) { return cb(err); } if (params.json) { return cb(null, buildResults); } doConsoleMessage(message, buildResults, params, cb); }); } /** * Perform the build * @param params * @param cb */ function doBuild(params, cb) { var doCall = function() { common.doApiCall(fhreq.getFeedHenryUrl(), createUri(params), params, i18n._("Error reading app: "), function(err, data) { if (err) { return cb(err); } var keys = []; if (data.cacheKey) { keys.push(data.cacheKey); } if (keys.length > 0) { async.map(keys, common.waitFor, function(err, results) { if (err) { if ( err[0].error === "Error status returned from SCM: 500") { return cb(i18n._("Git repository not found. Please check that all provided Git parameters are valid.")); } return cb(err); } if (results[0] && results[0][0] && results[0][0].action) { doSuccessOutcome(results, cb, params); } else { return cb(err, results); } }); } else { return cb(err, data); } }); }; doCall(); } /** * Create the URL of the built artifact * @param buildResults * @param cb * @returns {*} */ function getArtifactUrl(buildResults, cb) { if (buildResults.buildId) { //the self-managed build farm will return buildId. Call the artifacts endpoint to get the full url for downloading var buildId = buildResults.buildId; var uri = "box/srv/1.1/artifacts/" + buildId; fhreq.GET(fhreq.getFeedHenryUrl(), uri, function(err, data, raw, response) { if (err) { return cb(err); } if (response.statusCode !== 200 ) { return cb(raw); } buildResults.url = data.downloadurl; if (data.otaurl && data.otaurl.indexOf(".plist") >= 0) { //use the ios html file for ios OTA installation buildResults.ota_url = fhreq.getFeedHenryUrl() + "box/api/mas/storeitem/iosotahtml?url=" + data.otaurl; } else { buildResults.ota_url = data.otaurl; } return cb(null, buildResults); }); } else { return cb(null, buildResults); } } /** * Download the app if the download param is === true * @param params * @param assetUrl * @param path * @param cb * @returns {*} */ function downloadBuild(params, assetUrl, path, cb) { if (params.download !== 'true') { return cb(); } var uri = url.parse(assetUrl); var fileName = path + uri.pathname.split('/').pop(); var proto = uri.protocol === 'https:' ? https : http; log.silly(uri, "download uri"); log.silly(fileName, "download filename"); log.silly(proto, "download protocol"); var req = proto.get(uri, function(res) { var closedAlready = false; if (res.statusCode !== 200) { return cb(i18n._("Unexpected response code for file download: ") + res.statusCode + i18n._(" message: ") + res.body); } var stream = fs.createWriteStream(fileName); res.on('data', function(chunk) { stream.write(chunk); }); function finishOutoutStream() { if (!closedAlready) { closedAlready = true; return cb(undefined, { url: assetUrl, file: fileName }); } } stream.on('finish', function() { log.silly(i18n._('Finish stream event received')); finishOutoutStream(); }); stream.on('close', function() { log.silly(i18n._('close stream event received')); finishOutoutStream(); }); res.on('end', function() { log.silly(i18n._('End of netork stream received')); stream.end(); }); }); req.on('error', function(err) { return cb(i18n._("Error downloading build: ") + err.message); }); } /** * Created by maple on 16/10/9. */ seed.js const mongoose = require('mongoose'); var Campgrounds = require("./models/campground"); var Comment = require("./models/comment"); var Dp = require('./models/image'); // Seed data var data = [ { name: "Clouds Heaven", image : "https://www.minuteschool.com/wp-content/uploads/2019/07/blog_campping.jpeg", description: "Do ea ex enim ea. Incididunt id commodo nisi veniam do exercitation ullamco. Eiusmod aliquip id eu Lorem velit occaecat duis. Dolor duis sit nulla pariatur pariatur aute occaecat aliqua nostrud eu incididunt elit ad minim. Duis voluptate fugiat est consectetur aliquip ea excepteur laboris irure." }, { name: "Tree place ", image : "https://images.indulgexpress.com/uploads/user/imagelibrary/2019/10/24/original/Camp_diaries.jpg", description: "Do ea ex enim ea. Incididunt id commodo nisi veniam do exercitation ullamco. Eiusmod aliquip id eu Lorem velit occaecat duis. Dolor duis sit nulla pariatur pariatur aute occaecat aliqua nostrud eu incididunt elit ad minim. Duis voluptate fugiat est consectetur aliquip ea excepteur laboris irure." }, { name: "Mountains view", image : "https://cms.accuweather.com/wp-content/uploads/2019/03/camping-thumbnail.11.4920AM.png", description: "Do ea ex enim ea. Incididunt id commodo nisi veniam do exercitation ullamco. Eiusmod aliquip id eu Lorem velit occaecat duis. Dolor duis sit nulla pariatur pariatur aute occaecat aliqua nostrud eu incididunt elit ad minim. Duis voluptate fugiat est consectetur aliquip ea excepteur laboris irure." } ] function seedDB(){ Comment.remove({},function(err){ if(err) console.log(err) else console.log("Comments cleared!!"); }); // Removong campgrounds!! Campgrounds.remove({},function(err){ if(err){ console.log(err) } // console.log("DB cleared \n Feeding data....."); // iterate over each item/seed data.forEach(function(seed){ Campgrounds.create(seed,function(err,campground){ if(err){ console.log(err) } else{ // console.log("Data added to db!!"); // Create comments for the added campground Comment.create({ text : "this place is wonderful, hope we had internet here!!!", author : "Zaid" },function(err,comment){ if(err) console.log(err); else{ campground.comments.push(comment); campground.save(); // console.log("Comment created to the post") } }); } }); }); }); // Add campgrounds!! // Add comments } module.exports = seedDB;10-100 module.exports = function(expect) { let foo = function(x, ...items) { if(x === void 0 || x === null) { x = 24; } let y = 42; return [x, items, y]; }; expect(foo()).to.eql([24, [], 42]); expect(foo(1)).to.eql([1, [], 42]); expect(foo(1, 2)).to.eql([1, [2], 42]); expect(foo(1, 2, 3, 4)).to.eql([1, [2, 3, 4], 42]); };www/build/stencil-route-title.entry.js import { r as registerInstance, c as getElement } from './core-e86e2c51.js'; import { A as ActiveRouter } from './active-router-e2174b2d.js'; const RouteTitle = class { constructor(hostRef) { registerInstance(this, hostRef); this.titleSuffix = ''; this.pageTitle = ''; } updateDocumentTitle() { const el = this.el; if (el.ownerDocument) { el.ownerDocument.title = `${this.pageTitle}${this.titleSuffix || ''}`; } } componentWillLoad() { this.updateDocumentTitle(); } get el() { return getElement(this); } static get watchers() { return { "pageTitle": ["updateDocumentTitle"] }; } }; ActiveRouter.injectProps(RouteTitle, [ 'titleSuffix', ]); export { RouteTitle as stencil_route_title }; var path = require('path') var fs = require('fs') var generator = require('raml-generator') module.exports = generator({ templates: { '.gitignore': fs.readFileSync(path.join(__dirname, 'lib/templates/.gitignore.hbs'), 'utf8'), 'index.ts': fs.readFileSync(path.join(__dirname, 'lib/templates/index.ts.hbs'), 'utf8'), 'README.md': fs.readFileSync(path.join(__dirname, 'lib/templates/README.md.hbs'), 'utf8'), 'INSTALL.md': fs.readFileSync(path.join(__dirname, 'lib/templates/INSTALL.md.hbs'), 'utf8'), 'package.json': fs.readFileSync(path.join(__dirname, 'lib/templates/package.json.hbs'), 'utf8') }, partials: { auth: fs.readFileSync(path.join(__dirname, 'lib/partials/auth.ts.hbs'), 'utf8'), utils: fs.readFileSync(path.join(__dirname, 'lib/partials/utils.ts.hbs'), 'utf8'), client: fs.readFileSync(path.join(__dirname, 'lib/partials/client.ts.hbs'), 'utf8'), resources: fs.readFileSync(path.join(__dirname, 'lib/partials/resources.ts.hbs'), 'utf8') }, helpers: { stringify: require('javascript-stringify'), dependencies: require('./lib/helpers/dependencies'), requestSnippet: require('./lib/helpers/request-snippet'), parametersSnippet: require('./lib/helpers/parameters-snippet') } }) const AdditionalInfo = () => { return

Some information

}; const Component1 = ({ count, setCount }) => { return (
{count}
); }; const Parent = () => { const [count, setCount] = useState(0); return ( <> ); }; const AdditionalInfo = () => { return

Some information

}; const Component1 = ({ count, setCount, additionalInfo }) => { return (
{count} {additionalInfo}
); }; const Parent = ({ additionalInfo }) => { const [count, setCount] = useState(0); return ( <> ); }; const GrandParent = () => { return } />; }; const AdditionalInfo = () => { return

Some information

}; const Component1 = ({ count, setCount, children }) => { return (
{count} {children}
); }; const Parent = ({ children }) => { const [count, setCount] = useState(0); return ( <> {children} ); }; const GrandParent = () => { return ( ); }; $(document).ready(function(){ //CREATE if($('#create_camion').length) { $('#create_camion input.imagen').fileinput({ language: 'es', theme: 'fa', showPreview: true, showUpload: false, uploadAsync: true, maxFileConut: 1, autoReplate: true, browseOnZoneClick: true, allowedFileExtensions: ['jpg', 'jpeg', 'png', 'bmp', 'gif'], layoutTemplates: { actionUpload: '', actionDelete: '', }, previewSettings: { image: {width: "125px", height: "auto"}, } }); } //EDIT if($('#edit_camion').length) { var div = $('div.id_camion'); var id_camion = div.attr('id'); $.ajax({ type: 'GET', url: App.host + '/camion/' + id_camion + '/imagenes', success: function(response) { $.each($('.imagen'), function(i, element) { var exists = false; var data = null; $.each(response.data, function(key, value) { if($(element).attr('id') == key.toString()) { exists = true; data = value; } }); if(exists) { $(element).fileinput({ language: 'es', theme: 'fa', showPreview: true, showUpload: false, uploadUrl: false, uploadAsync: true, maxFileCount: 1, autoReplace: true, initialPreview: data.url, initialPreviewAsData: true, initialPreviewFileType: 'image', initialPreviewConfig: [data.data], dropZoneTitle: '

Selecciona ó arrastra una imagen

', dropZoneClickTitle: '', allowedFileExtensions: ['jpg', 'jpeg', 'png', 'bmp', 'gif'], overwriteInitial: true, initialCaption: [data.data.caption], layoutTemplates: { actionUpload: '', }, previewSettings: { image: {width: "120px", height: "100px", 'max-width': "100%",'max-height': "100%"} }, deleteExtraData: { _method: 'delete', _token: App.csrfToken } }); $(element).on("filepredelete", function(jqXHR) { var abort = true; if (confirm("¿Estás seguro de querer eliminar la imagen?")) { abort = false; } return abort; }); $(element).on('filedeleted', function(event, key){ swal('¡Imagen Eliminada!', "", "success"); }); } else { $(element).fileinput({ language: 'es', theme: 'fa', showPreview: true, showUpload: false, browseOnZoneClick: true, uploadUrl: false, uploadAsync: true, maxFileCount: 1, dropZoneTitle: '

Selecciona ó arrastra una imagen

', dropZoneClickTitle: '', autoReplace: true, allowedFileExtensions: ['jpg', 'jpeg', 'png', 'bmp', 'gif'], layoutTemplates: { actionUpload: '', actionDelete: '' }, previewSettings: { image: {width: "120px", height: "100px", 'max-width': "100%",'max-height': "100%"} } }); } }); $('div.fileinput-remove').attr('style', 'display:none'); } }); } //GENERALES $('input.cubicacion').keyup(function(){ calcularCubicaciones(); }); $('input.cubicacion').change(function(){ calcularCubicaciones(); }); function calcularCubicaciones() { var dim = 0; var ancho = parseFloat($('input.ancho').val()); var largo = parseFloat($('input.largo').val()); var alto = parseFloat($('input.alto').val()); var gato = parseFloat($('input.gato').val()); var dism = parseFloat($('input.disminucion').val()); var ext = parseFloat($('input.extension').val()); if(!isNaN(ancho) && !isNaN(largo) && !isNaN(alto)) { dim = ancho*largo*alto; if(!isNaN(gato)) { dim -= gato; } if(!isNaN(ext)) { dim += (ancho*largo*ext); } if(!isNaN(dism)) { dim -= dism; } } $('input.real').val(dim.toFixed(2)); $('input.pago').val(Math.round(dim.toFixed(2))); } });import { cilArrowLeft, cilPrint } from '@coreui/icons' import CIcon from '@coreui/icons-react' import { CTable, CTableHeaderCell, CTableRow, CTableDataCell, CTableHead, CTableBody, CCardTitle, CCol, CCardText, CCardBody, CCard, CCardHeader, CRow, } from '@coreui/react' import React, { useEffect, useState } from 'react' import { useHistory, useRouteMatch } from 'react-router-dom' import { SampleGambar } from 'src/assets' import Banner from '../Banner' import { getDiagnosaById } from 'src/context/actions/Diagnosa' import { LoadingSkeletonHasilDiagnosa } from '../../../Components' import getImage from 'src/context/actions/Files/getImage' const HasilKonsultasi = () => { const history = useHistory() const match = useRouteMatch() const { params } = match const [diagnosa, setDiagnosa] = useState('') // Get hasil diagnosa by id pasien useEffect(() => { getDiagnosaById(params.id, setDiagnosa, history) }, [params]) useEffect(() => { window.scrollTo(0, 600) }, []) const goBackToPrevPage = (e) => { e.preventDefault() history.goBack() } const dataGejala = !diagnosa ? [] : diagnosa.data_gejala const dataSolusi = !diagnosa ? [] : diagnosa.data_saran_pengobatan const dataPenyakitLain = !diagnosa ? [] : diagnosa.hasil_diagnosa_penyakit_lain const dataHasilPakar = !diagnosa ? '' : diagnosa.hasil_pakar return (
{/* Banner */} {/* Body Content */}
{/* Loading Skeleton */} {!diagnosa && }
goBackToPrevPage(e)}> Kembali ke halaman sebelumnya

Hasil Diagnosa

{/* Gejala */} {diagnosa && ( <>
# Kode Gejala yang Dialami Kondisi {dataGejala.map((item, index) => ( {index + 1} {item.id_gejala} {item.nm_gejala} {item.nm_kondisi} ))}
{/* Diagnosa Penyakit */}
Diagnosa Penyakit
{'gambar-penyakit'} {dataHasilPakar.nm_penyakit} / CF ({dataHasilPakar.nilai_cf * 100} %) {dataHasilPakar.deskripsi}
{/* Saran Pengobatan */}
Saran Pengobatan
    {dataSolusi.map((item, idx) => (
  • {item.solusi}
  • ))}
{/* Penyakit Lain */}
Kemungkinan Penyakit Lain
    {dataPenyakitLain.map((item, idx) => (
  • {item.nm_penyakit} ({item.nilai_cf} / {item.nilai_cf * 100} %)
  • ))}
)}
) } export default HasilKonsultasi src/components/Questions/QuestionResults.js0 import React from 'react'; import {connect} from "react-redux"; import Row from "react-bootstrap/Row"; import QuestionResultItem from "./QuestionResultItem"; function QuestionResults(props) { const {optionOne, optionTwo, authedUser} = props const totalVotes = optionOne.votes.length + optionTwo.votes.length return (
); } function mapStateToProps({authedUser}) { return { authedUser } } export default connect(mapStateToProps)(QuestionResults); 1-10 'use strict'; angular.module('dataGeyserApp') .controller('MainCtrl', function ($scope, $http, socket, Interceptor) { $scope.awesomeTweets = []; $scope.tweetParser = []; $scope.topic = "ebola"; $scope.streaming = false; window.onkeydown = checkKeyPressed; var tweetTempStorage = {}; ///////// keydown event listener function...should probably go elsewhere ////////////// function checkKeyPressed(e){ if (e.keyCode === 32) { e.preventDefault(); vrControls.zeroSensor(); } if (e.keyCode === 13) { e.preventDefault(); $scope.getTopic($scope.topic); } if (e.keyCode === 81){ e.preventDefault(); $('#gui').toggle(1000); } } ////////// scope methods /////////// $http.get('/api/tweets').success(function(awesomeTweets) { $scope.awesomeTweets = awesomeTweets; // creates object param for each topic in DB with total num of tweets for (var i = 0; i < awesomeTweets.length; i++){ tweetTempStorage[awesomeTweets[i].keyword] = tweetTempStorage[awesomeTweets[i].keyword] || 0; tweetTempStorage[awesomeTweets[i].keyword]++; } // changes db summary object into array for (var key in tweetTempStorage) { var newBucket = {}; newBucket.topic = key; newBucket.numTweets = tweetTempStorage[key]; if (tweetTempStorage[key] > 2000) { newBucket.isOptimal = "Yes"; } else { newBucket.isOptimal = "No"; } $scope.tweetParser.push(newBucket); } // socket.syncUpdates('tweet', $scope.awesomeTweets); }); $scope.$on('$destroy', function () { socket.unsyncUpdates('tweet'); }); // starts twitter api stream $scope.chooseTopic = function(topic){ $scope.streaming = true; $http.post('/api/tweets/getTweets/' + topic).success(function(){ console.log('post success'); }); } // stops twitter stream $scope.stopTopic = function(topic){ $scope.streaming = false; $http.put('/api/tweets/getTweets/' + topic).success(function(){ console.log('stopped stream'); }); } // fetches tweets matching topic from DB $scope.getTopic = function(topic) { Interceptor.start(); // $('#gui').hide(); $http.get('/api/tweets/getTweets/' + topic) .success(function(data){ Interceptor.end(); renderTweets(data); }); } // destroys all tweets matching topic in DB $scope.destroyTopic = function(topic) { Interceptor.start(); $http.delete('/api/tweets/getTweets/' + topic).success(function(){ Interceptor.end(); console.log(topic, 'destroyed'); }) } }); juan-rsk/rns-manager-react import reducer from './reducer'; import { REQUEST_REGISTRAR_GET_COST, RECEIVE_REGISTRAR_GET_COST, REQUEST_REGISTRAR_COMMIT, RECEIVE_REGISTRAR_COMMIT, ERROR_REGISTRAR_COMMIT, RECEIVE_REGISTRAR_REVEAL_COMMIT, REQUEST_REGISTRAR_REVEAL_COMMIT, RECEIVE_CAN_REVEAL_COMMIT, ERROR_REGISTRAR_REVEAL_COMMIT, REGISTRAR_COMMIT_CONFIRMED, REVEAL_COMMIT_CONFIRMED, } from './types'; describe('register reducer', () => { const initialState = { gettingCost: false, committing: false, committed: false, hash: null, revealing: false, revealed: false, waiting: false, canReveal: false, commitConfirmed: null, revealConfirmed: null, gettingConversionRate: false, conversionRate: null, setupAddr: true, successTx: '', errorMessage: '', }; it('should return the initial state', () => { expect(reducer(undefined, {})) .toEqual(initialState); }); it('should handle REQUEST_REGISTRAR_GET_COST', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_GET_COST, duration: 12, }), ) .toEqual({ gettingCost: true, duration: 12, }); }); it('should handle RECEIVE_REGISTRAR_GET_COST', () => { expect( reducer({}, { type: RECEIVE_REGISTRAR_GET_COST, rifCost: 12, }), ).toEqual({ gettingCost: false, rifCost: 12, }); }); it('should handle REQUEST_REGISTRAR_GET_COST and RECEIVE_REGISTRAR_GET_COST', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_GET_COST, duration: 23, }), ) .toEqual({ gettingCost: true, duration: 23, }); expect( reducer({ gettingCost: true, duration: 23, }, { type: RECEIVE_REGISTRAR_GET_COST, rifCost: 45, }), ).toEqual({ gettingCost: false, rifCost: 45, duration: 23, }); }); it('should handle REQUEST_REGISTRAR_COMMIT', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_COMMIT, }), ) .toEqual({ committing: true, errorMessage: '', }); }); it('should handle RECEIVE_REGISTRAR_COMMIT', () => { expect( reducer({}, { type: RECEIVE_REGISTRAR_COMMIT, hash: 'sarasa', }), ).toEqual({ committing: false, committed: true, hash: 'sarasa', waiting: true, commitConfirmed: null, }); }); it('should handle RECEIVE_REGISTRAR_COMMIT with commitConfirmed', () => { expect( reducer({}, { type: RECEIVE_REGISTRAR_COMMIT, hash: 'sarasa', commitConfirmed: true, }), ).toEqual({ committing: false, committed: true, hash: 'sarasa', waiting: true, commitConfirmed: true, }); }); it('should handle ERROR_REGISTRAR_COMMIT', () => { expect( reducer({}, { type: ERROR_REGISTRAR_COMMIT, message: 'error', }), ).toEqual({ committing: false, committed: false, waiting: false, errorMessage: 'error', hash: null, }); }); it('should handle REQUEST_REGISTRAR_COMMIT and RECEIVE_REGISTRAR_COMMIT and REGISTRAR_COMMIT_CONFIRMED', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_COMMIT, }), ) .toEqual({ committing: true, errorMessage: '', }); expect( reducer({ committing: true, }, { type: RECEIVE_REGISTRAR_COMMIT, hash: 'sarasa', }), ).toEqual({ committing: false, committed: true, hash: 'sarasa', waiting: true, commitConfirmed: null, }); expect( reducer({ committing: false, committed: true, hash: 'sarasa', waiting: true, commitConfirmed: null, }, { type: REGISTRAR_COMMIT_CONFIRMED, }), ).toEqual({ committing: false, committed: true, hash: 'sarasa', waiting: true, commitConfirmed: true, }); }); it('should handle REQUEST_REGISTRAR_COMMIT and ERROR_REGISTRAR_COMMIT', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_COMMIT, }), ) .toEqual({ committing: true, errorMessage: '', }); expect( reducer({ committing: true, }, { type: ERROR_REGISTRAR_COMMIT, message: '', }), ).toEqual({ committing: false, committed: false, errorMessage: '', waiting: false, hash: null, }); }); it('should handle REQUEST_REGISTRAR_REVEAL_COMMIT', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_REVEAL_COMMIT, }), ) .toEqual({ revealing: true, errorMessage: '', }); }); it('should handle RECEIVE_REGISTRAR_REVEAL_COMMIT', () => { expect( reducer({}, { type: RECEIVE_REGISTRAR_REVEAL_COMMIT, }), ).toEqual({ revealing: false, revealed: true, }); }); it('should handle REQUEST_REGISTRAR_REVEAL_COMMIT and RECEIVE_REGISTRAR_REVEAL_COMMIT', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_REVEAL_COMMIT, }), ) .toEqual({ revealing: true, errorMessage: '', }); expect( reducer({ revealing: true, }, { type: RECEIVE_REGISTRAR_REVEAL_COMMIT, }), ).toEqual({ revealing: false, revealed: true, }); }); it('should handle REQUEST_REGISTRAR_REVEAL_COMMIT and RECEIVE_REGISTRAR_REVEAL_COMMIT and REVAL_COMMIT_CONFIRMED', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_REVEAL_COMMIT, }), ) .toEqual({ revealing: true, errorMessage: '', }); expect( reducer({ revealing: true, }, { type: RECEIVE_REGISTRAR_REVEAL_COMMIT, }), ).toEqual({ revealing: false, revealed: true, }); expect( reducer({ revealing: false, revealed: true, }, { type: REVEAL_COMMIT_CONFIRMED, }), ).toEqual({ revealing: false, revealed: true, revealConfirmed: true, }); }); it('should handle ERROR_REGISTRAR_REVEAL_COMMIT', () => { expect( reducer({}, { type: ERROR_REGISTRAR_REVEAL_COMMIT, }), ).toEqual({ revealing: false, revealed: false, }); }); it('should handle REQUEST_REGISTRAR_REVEAL_COMMIT and ERROR_REGISTRAR_REVEAL_COMMIT', () => { expect( reducer({}, { type: REQUEST_REGISTRAR_REVEAL_COMMIT, }), ) .toEqual({ revealing: true, errorMessage: '', }); expect( reducer({ revealing: true, }, { type: ERROR_REGISTRAR_REVEAL_COMMIT, }), ).toEqual({ revealing: false, revealed: false, }); }); it('should handle REGISTRAR_COMMIT_CONFIRMED true', () => { expect( reducer({}, { type: REGISTRAR_COMMIT_CONFIRMED, }), ).toEqual({ commitConfirmed: true, }); }); it('should handle REVEAL_COMMIT_CONFIRMED', () => { expect( reducer({}, { type: REVEAL_COMMIT_CONFIRMED, }), ).toEqual({ revealConfirmed: true, }); }); it('should handle RECEIVE_CAN_REVEAL_COMMIT false', () => { expect( reducer({}, { type: RECEIVE_CAN_REVEAL_COMMIT, canReveal: false, }), ).toEqual({ canReveal: false, waiting: true, }); }); it('should handle RECEIVE_CAN_REVEAL_COMMIT true', () => { expect( reducer({}, { type: RECEIVE_CAN_REVEAL_COMMIT, canReveal: true, }), ).toEqual({ canReveal: true, waiting: false, }); }); it('should return the initial state when action is SALT_NOT_FOUND', () => { expect(reducer(undefined, { type: 'SALT_NOT_FOUND', })) .toEqual(initialState); }); it('should return the initial state when action is not implemented', () => { expect(reducer(undefined, { type: 'NOT_IMPLEMENTED', })) .toEqual(initialState); }); it('should set the checkbox to false', () => { const expected = { ...initialState, setupAddr: false, }; expect(reducer(undefined, { type: 'TOGGLE_SETUP_ADDRESS', setupAddr: false, })) .toEqual(expected); }); }); 'use strict'; //zip -r ../popcheck-lambda.zip * process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT']; var AWS = require('aws-sdk'); var async = require('async'); var https = require('https'); var sql = require('mssql'); const uuidv4 = require('uuid/v4'); var pool; //for database connection const POP_CHECK_API_URL = 'a.popcheckapp.com'; var sqs = new AWS.SQS({region: process.env.AWS_SQS_REGION}); function receiveMessages(callback) { var params = { QueueUrl: process.env.AWS_SQS_QUEUE_URL, MaxNumberOfMessages: 1, //limit to 1 to get max execution time WaitTimeSeconds: 0 }; sqs.receiveMessage(params, function(err, data) { if (err) { console.error(err, err.stack); callback(err); } else { callback(null, data.Messages); } }); } function joinAndDelimit(obj) { return obj.map(function(item) { if (item === null) { return 'NULL'; } if (typeof item === 'string') { return ("'" + item.replace(/'/g, "") + "'"); } else { return item; } }).join(','); } function processMessage(message, callback) { async.waterfall([ function checkMessage(next) { let body = JSON.parse(message.Body); if (!('Message' in body)) { next('Bad message format'); } else { next(null); } }, function getPOPCheckToken(next) { let params = { email: process.env.POPCHECK_API_EMAIL, password: . }; let options = { host: POP_CHECK_API_URL, port: '443', path: '/v2/login', method: 'POST', headers: { 'Content-Type': 'application/json;charset=UTF-8' } }; var data = ''; var req = https.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { data = JSON.parse(data); next(null, data.token); }); }); req.on('error', (e) => { next(e.message); }); req.write(JSON.stringify(params)); req.end(); }, function getVisit(token, next) { let body = JSON.parse(message.Body); let visitUUID = body.Message; let options = { host: POP_CHECK_API_URL, port: '443', path: '/v2/visits/client/' + visitUUID + '?forceRequireSurveyQuestionSurveySectionPhotoTag=1', method: 'GET', headers: { 'Authorization': 'Bearer ' + token } }; var data = ''; var req = https.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { data = JSON.parse(data); if (data.hasOwnProperty('error')) { //console.log('error with visitUUID ' + visitUUID) next(data.error); } else { next(null, data); } }); }); req.on('error', (e) => { next(e.message); }); req.end(); }, function writeToDatabaseVisit(data, next) { let visitFields = 'local_visit_id, visitUUID, reference, locationName, locationReference, locationUUID, campaignName, campaignReference, campaignUUID, clientName, clientReference, clientUUID, userName, userUUID, scheduleStartDate, scheduleEndDate, actualStartDate, actualEndDate, startLat, startLng, startAccuracy, endLat, endLng, endAccuracy'; //generate unique local visit id (uuid in this case) const local_visit_id = uuidv4(); // ⇨ '416ac246-e7ac-49ff-93b4-f7e94d997e6b' var visit = []; visit.push(local_visit_id, data.uuid, data.reference, data.Location.name, data.Location.reference, data.Location.uuid, data.Campaign.name, data.Campaign.reference, data.Campaign.uuid, data.Campaign.Client.name, data.Campaign.Client.reference, data.Campaign.Client.uuid, data.User.name, data.User.uuid, data.scheduleStartDate, data.scheduleEndDate, data.actualStartDate, data.actualEndDate, data.startLat, data.startLng, data.startAccuracy, data.endLat, data.endLng, data.endAccuracy); visit = joinAndDelimit(visit); var query = 'insert into ' + process.env.DBS_TABLE_NAME_VISITS + ' (' + visitFields + ') values (' + visit + ');'; var request = new sql.Request(pool).query(query, (err, result) => { if (err) { console.log('Visit insert error'); console.log(err); console.log(query); } next(null, local_visit_id, data); }); }, function writeToDatabaseResponses(local_visit_id, data, next) { let responseFields = 'local_visit_id, visitUUID, surveySectionReference, surveySectionName, surveySectionSortOrder, surveyQuestionReference, surveyQuestionType, surveyQuestionSortOrder, surveyQuestion, answer'; var responses1 = []; var responses2 = []; for (var i = 0; i < data.SurveyResponses.length; i++) { var sr = data.SurveyResponses[i]; var response = []; response.push(local_visit_id, data.uuid, sr.SurveyQuestion.SurveySection.reference, sr.SurveyQuestion.SurveySection.name, sr.SurveyQuestion.SurveySection.sortOrder, sr.SurveyQuestion.reference, sr.SurveyQuestion.type, sr.SurveyQuestion.sortOrder, sr.SurveyQuestion.question, sr.answer); response = joinAndDelimit(response); if (responses1.length < 1000) { responses1.push(response); } else { responses2.push(response); } } var query1 = 'insert into ' + process.env.DBS_TABLE_NAME_RESPONSES + ' (' + responseFields + ') values (' + responses1.join('),(') + ');'; var query2 = 'insert into ' + process.env.DBS_TABLE_NAME_RESPONSES + ' (' + responseFields + ') values (' + responses2.join('),(') + ');'; if (responses1.length) { var request1 = new sql.Request(pool).query(query1, (err, result) => { if (err) { console.log('Responses1 insert error'); console.log(err); console.log(query1); } if (responses2.length) { var request2 = new sql.Request(pool).query(query2, (err, result) => { if (err) { console.log('Responses2 insert error'); console.log(err); console.log(query2); } next(err, local_visit_id, data); }); } else { next(null, local_visit_id, data); } }); } else { next(null, local_visit_id, data); } }, function writeToDatabasePhotos(local_visit_id, data, next) { let photoFields = 'local_visit_id, visitUUID, photoTagReference, photoTagName, photoTagPrefix, url, lat, lng, accuracy'; let photos = []; for (var i = 0; i < data.Photos.length; i++) { let p = data.Photos[i]; let photo = []; photo.push(local_visit_id, data.uuid, p.PhotoTag.reference, p.PhotoTag.name, p.PhotoTag.prefix, p.url, p.lat, p.lng, p.accuracy); photo = joinAndDelimit(photo); photos.push(photo); } var query = 'insert into ' + process.env.DBS_TABLE_NAME_PHOTOS + ' (' + photoFields + ') values (' + photos.join('),(') + ');'; if (photos.length) { var request = new sql.Request(pool).query(query, (err, result) => { if (err) { console.log('Photos insert error'); console.log(err); console.log(query); } next(err, result); }); } else { next(null); } } ], function(err) { if (err) { console.log(err); } //try to delete whether error or not if (message.hasOwnProperty('ReceiptHandle')) { sqs.deleteMessage({ QueueUrl: process.env.AWS_SQS_QUEUE_URL, ReceiptHandle: message.ReceiptHandle }, function(e) { if (e) { console.log(e); } if (e || err) { callback(null, "error"); } else { callback(null, "success"); } }); } else { if (err) { callback(null, "error"); } else { callback(null, "success"); } } } ); } function handleSQSMessages(context, callback) { receiveMessages(function(err, messages) { if (messages && messages.length > 0) { var promises = []; messages.forEach(function(message) { promises.push(function(cb) { processMessage(message, cb); }); }); async.parallel(promises, function(err) { if (err) { console.error(err, err.stack); callback(err); } else { if (context.getRemainingTimeInMillis() > 10000) { //check at least 10s left handleSQSMessages(context, callback); } else { callback(null, "pause"); } } }); } else { callback(null, "success"); } }); } exports.handler = function(event, context, callback) { //By default, the callback will wait until the Node.js runtime event loop is empty before freezing the process and returning the results to the caller context.callbackWaitsForEmptyEventLoop = false let config = { user: process.env.DBS_USER, password: .DBS_PASSWORD, server: process.env.DBS_SERVER, database: process.env.DBS_DATABASE }; pool = new sql.ConnectionPool(config, function(err) { if (err) { console.log(err); callback(err); return; } if (event.hasOwnProperty('Messages') && event.Messages.length > 0) { //TESTING processMessage(event.Messages[0], callback); } else { handleSQSMessages(context, callback); } } ); }; 10-100 import { User } from 'models/user'; export default class { constructor( options ) { this.userId = options.userId; this.user = null; } execute() { return getUser.call( this ) .bind( this ) .then( setUser ) .then( returnRecipes ); } } ////////////////// ////// Private function getUser() { return User .forge( { id: this.userId } ) .fetch( { withRelated: [ { recipes: qb => { qb .where( { visibility: 1 } ) .orderBy( 'name', 'asc' ); } } ] } ); } function setUser( user ) { this.user = user; } function returnRecipes() { return this.user.related( 'recipes' ); }// 首页 FlowRouter.route('/', { action: function() { BlazeLayout.render("mainLayout", {content: "home"}); } }); //概况 var overview = FlowRouter.group({ prefix: "/overview", name: 'overviewGroup' }); overview.route('/', { name: 'overview', action: function() { BlazeLayout.render("mainLayout", {content: "overview"}); } });13020030191/reacr-demo import React, { Component } from 'react' import { Route, Switch } from 'react-router-dom' import { Input } from 'antd' import PageHeaderWrapper from '../../../components/PageHeaderWrapper' import { getRouterData } from '../../../router/router' import { getRoutes } from '../../../utils/utils' class List extends Component { render () { const { location, match } = this.props const routerData = getRouterData() const routes = getRoutes(match.path, routerData) const mainSearch = (
{console.log(value)}} style={{width: 522}} />
) return ( { routes.map(item => ( )) } ) } } export default List 'use strict' require('./package') // require('./basic') require('./gallery/_index') import * as assert from '../assert.js'; import Builder from '../Builder.js'; async function test() { let builder = (new Builder()) .Type().End() .Function().End() .Export() .Function("foo") .End() .Code() .Function("foo", { params: ["i32"], ret: "i32" }, ["i32"]) .Block("i32") .Loop("i32", b => b.GetLocal(1) .GetLocal(0) .I32Eqz() .BrIf(1) .Call(1) .GetLocal(1) .I32Add() .SetLocal(1) .GetLocal(0) .I32Const(1) .I32Sub() .SetLocal(0) .Br(0) ) .End() .End() .Function("bar", { params: [], ret: "i32" }) .I32Const(42) .Return() .End() .End() const bin = builder.WebAssembly().get(); const {instance} = await WebAssembly.instantiate(bin, {}); const iters = 100000 for (let i = 0; i < 100; i++) assert.eq(instance.exports.foo(iters), 42 * iters); } assert.asyncTest(test()); nedshopov/GeoAppFront import L from 'leaflet'; import {useMap} from 'react-leaflet'; import {useEffect} from 'react'; import 'leaflet-gpx'; const Track = () => { var map = useMap(); var gpx = test; useEffect(() => { let track = new L.GPX(gpx, { async: true }).on('loaded', function (e) { console.log(e); map.fitBounds(e.target.getBounds()); }).addTo(map); console.log(track); }, []) return (
test
) } export default Track benchmark/bench.js0 import Conflux from '../write.js'; const { WritableStream, Response, Benchmark, Blob, JSZip, zip, } = window; zip.useWebWorkers = false; const uint8 = new Uint8Array(256); for (let i = 0; i < uint8.length; i++) uint8[i] = i; const blob = new Blob(new Array(2000).fill(uint8)); let text = null; let uInt8 = null; const suite = new Benchmark.Suite(); const file = { name: 'Hello.txt', stream: () => new Response(blob).body }; // add tests suite .add('JSZip - from Blob', { defer: true, fn(p) { const jsZip = new JSZip(); jsZip.file('Hello.txt', blob); jsZip.generateAsync({ type: 'blob' }).then(() => p.resolve()); }, }) .add('JSZip - from Uint8Array', { defer: true, fn(p) { const jsZip = new JSZip(); jsZip.file('Hello.txt', uInt8); jsZip.generateAsync({ type: 'blob' }).then(() => p.resolve()); }, }) .add('JSZip - from String', { defer: true, fn(p) { const jsZip = new JSZip(); jsZip.file('Hello.txt', text); jsZip.generateAsync({ type: 'blob' }).then(() => p.resolve()); }, }) .add('zip.js - from Blob', { defer: true, fn(p) { // use a BlobWriter to store the zip into a Blob object zip.createWriter(new zip.BlobWriter('application/zip'), (writer) => { // use a BlobReader object to read the data stored into blob variable writer.add('Hello.txt', new zip.BlobReader(blob), () => { // close the writer and calls callback function writer.close(() => p.resolve()); }); }, console.error, { dontDeflate: true }); }, }) .add('zip.js - from Text', { defer: true, fn(p) { // use a BlobWriter to store the zip into a Blob object zip.createWriter(new zip.BlobWriter('application/zip'), (writer) => { // use a BlobReader object to read the data stored into blob variable writer.add('Hello.txt', new zip.BlobReader(blob), () => { // close the writer and calls callback function writer.close(() => p.resolve()); }); }, console.error, { dontDeflate: true }); }, }) .add('Conflux - Response to blob', { defer: true, fn(p) { const { writable, readable } = new Conflux(); const writer = writable.getWriter(); const res = new Response(readable, { headers: { 'content-type': 'application/zip' } }); res.blob().then(() => p.resolve()); writer.write(file); writer.close(); }, }) .add('Conflux - pipeTo Writable Blob builder', { defer: true, fn(p) { const { writable, readable } = new Conflux(); const writer = writable.getWriter(); const chunks = []; const ws = new WritableStream({ write(chunk) { chunks.push(chunk); }, close() { // eslint-disable-next-line no-new new Blob(chunks, { type: 'application/zip' }); p.resolve(); }, }); readable.pipeTo(ws); writer.write(file); writer.close(); }, }) .add('Conflux - pipeTo noop Writable', { defer: true, fn(p) { const { writable, readable } = new Conflux(); const writer = writable.getWriter(); const ws = new WritableStream({ write() {}, close() { p.resolve(); }, }); readable.pipeTo(ws); writer.write(file); writer.close(); }, }) // add listeners .on('cycle', (event) => { const p = document.createElement('p'); p.innerText = String(event.target); document.body.appendChild(p); console.log(String(event.target)); }) .on('complete', () => { document.getElementById('loading').remove(); console.log(`Fastest is ${this.filter('fastest').map('name')}`); }); new Response(blob).arrayBuffer().then((buf) => { new Response(blob).text().then((txt) => { uInt8 = new Uint8Array(buf); text = txt; suite.run({ async: true }); }); }); export const CHANGE_SETTING = "CHANGE_SETTING"; // 改变系统设置 export const CLOSE_SIDEBAR = "CLOSE_SIDEBAR"; // 关闭sidebar export const CHANGE_ACTIVEINDEX = "CHANGE_ACTIVEINDEX"; // 改变活动的菜单项index export const TOGGLE_DEVICE = "TOGGLE_DEVICE"; // 切换设备 export const TOGGLE_MESSAGEBOX = "TOGGLE_MESSAGEBOX"; // 切换设备 export const CHANGE_TABS = "CHANGE_TABS"; // 页签 export const SET_TOKEN = "SET_TOKEN"; // 设置登录token export const SET_MENULIST = "SET_MENULIST"; // 设置菜单栏 export const GET_MENU_NAME = "GET_MENU_NAME"; // 获取菜单名称列表 export const CHANGE_LOCALE = "CHANGE_LOCALE"; // 切换中英文 // Socket export const SOCKET_ONOPEN = "✅ Socket connected!"; export const SOCKET_ONCLOSE = "❌ Socket disconnected!"; export const SOCKET_ONERROR = "❌ Socket Error!!!"; export const SOCKET_ONMESSAGE = "Websocket message received"; export const SOCKET_RECONNECT = "Websocket reconnected"; export const SOCKET_RECONNECT_ERROR = "Websocket is having issues reconnecting.."; const mongoose = require('mongoose') const path = require('path') const Telegraf = require('telegraf') const I18n = require('telegraf-i18n') const { onlyAdmin, userUpdate, groupUpdate, } = require('./middlewares') const { handleMessage, handleHelp, handlePing, handleWelcome, handleBanan, handleKick, handleDelete, handleAdminWelcome, handleAdminWelcomeGif, handleAdminWelcomeText, handleAdminExtra, handleReset, handleSendSettingsJson, handleExtra, } = require('./handlers') global.botStart = new Date() mongoose.connect(process.env.MONGODB_URI, { useCreateIndex: true, useNewUrlParser: true, }) const db = mongoose.connection db.on('error', (err) => { console.log('error', err) }) const i18n = new I18n({ directory: path.resolve(__dirname, 'locales'), defaultLanguage: 'ru', sessionName: 'session', useSession: true, }) const bot = new Telegraf(process.env.BOT_TOKEN) bot.telegram.getMe().then((botInfo) => { bot.options.username = botInfo.username }) bot.use((ctx, next) => { ctx.ms = new Date() next() }) bot.use(i18n.middleware()) bot.use(async (ctx, next) => { userUpdate(ctx) await groupUpdate(ctx) await next(ctx) const ms = new Date() - ctx.ms console.log('Response time %sms', ms) }) bot.command('help', handleHelp) bot.command('ping', handlePing) bot.command('banan', handleBanan) bot.command('kick', handleKick) bot.command('del', handleDelete) bot.hears('!welcome', onlyAdmin, handleAdminWelcome) bot.hears('!gif', onlyAdmin, handleAdminWelcomeGif) bot.hears('!text', onlyAdmin, handleAdminWelcomeText) bot.hears(/^!extra($|\s.*)/, onlyAdmin, handleAdminExtra) bot.hears('!reset', onlyAdmin, handleReset) bot.hears('!json', onlyAdmin, handleSendSettingsJson) bot.hears(/^#/, handleExtra) bot.on('new_chat_members', handleWelcome) bot.on('message', handleMessage) bot.catch((error) => { console.log('Ooops', error) }) bot.launch() import FontAwesomeSelectModule from './fontAwesomeSelect' import FontAwesomeSelectController from './fontAwesomeSelect.controller'; import FontAwesomeSelectComponent from './fontAwesomeSelect.component'; import FontAwesomeSelectTemplate from './fontAwesomeSelect.html'; describe('FontAwesomeSelect', () => { let $rootScope, makeController; beforeEach(window.module(FontAwesomeSelectModule)); beforeEach(inject((_$rootScope_) => { $rootScope = _$rootScope_; makeController = () => { return new FontAwesomeSelectController(); }; })); describe('Module', () => { // top-level specs: i.e., routes, injection, naming }); describe('Controller', () => { // controller specs it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller let controller = makeController(); expect(controller).to.have.property('name'); }); }); describe('Component', () => { // component/directive specs let component = FontAwesomeSelectComponent; it('includes the intended template',() => { expect(component.template).to.equal(FontAwesomeSelectTemplate); }); it('invokes the right controller', () => { expect(component.controller).to.equal(FontAwesomeSelectController); }); }); }); const graphql = require("graphql"); const NotificationType = require("./NotificationType"); const { GraphQLObjectType, GraphQLString, GraphQLBoolean, GraphQLID, GraphQLInt, GraphQLList, } = graphql; const EmployeeType = new GraphQLObjectType({ name: "EmployeeType", fields: () => ({ _id: { type: GraphQLID, }, firstName: { type: GraphQLString }, lastName: { type: GraphQLString }, email: { type: GraphQLString }, phoneNumber: { type: GraphQLString }, profilePicture: { type: GraphQLString }, employeeRole: { type: new GraphQLList(GraphQLString) }, permanentPasswordSet: { type: GraphQLBoolean }, password: { type: GraphQLString }, notifications: { type: new GraphQLList(NotificationType) }, tokenCount: { type: GraphQLInt }, createdAt: { type: GraphQLString }, }), }); module.exports = EmployeeType; /* @flow */ import basic from './basic'; import disabled from './disabled'; import element from './element'; import icons from './icons'; import importSyntax from './importSyntax'; import maxWidth from './maxWidth'; import selected from './selected'; export default [ importSyntax, basic, selected, icons, disabled, maxWidth, element ]; /* This is the override file for math4.js. If you copy * math4-overrides.js.dist to math4-overrides.js you can edit the * values contained in this file and they will override the css values * normally used for math4. This includes anything you can accomplish with * jQuery and provides a lot of flexibility. * * If you upgrade your machine this file will not be overwritten, however, the * math4.js and math4-overrides.js.dist file may change. If this happens it * may cause problems with your theme until your reconcile the changes with * your modifactions here. (Similar to how localOverrides.conf works.) */ $(function () { /* This changes the WeBWorK Logo on the top left to a new image */ // $('.webwork_logo a img').attr('src','new-path-here'); /* This changes the MAA Logo on the top to a new image */ $('.maa_logo a img').attr('src','/webwork2_files/themes/math4/images-custom/maa_logo_small_black.png'); $('#mainform input[type="reset"]').addClass('btn btn-small'); $('#mainform input[name="edit_local"]').removeClass('btn-primary'); $('#mainform input[name="new_local_set"]').removeClass('btn-primary'); $('#mainform input[name="lib_view"]').addClass('btn-primary'); $('#mainform input[name="lib_view_bpl"]').addClass('btn-primary'); $('#mainform input[name="lib_view_bplen"]').addClass('btn-primary'); $('#mainform input[name="view_mysets_set"]').addClass('btn-primary'); $('#mainform input[name="view_local_set"]').addClass('btn-primary'); $('#mainform input[name="lib_view_spcf"]').addClass('btn-primary'); $('#mainform input[name="view_setdef_set"]').addClass('btn-primary'); $('#mainform select[name=max_shownt]').addClass('input-small').removeClass('input-xxlarge'); }); console.log('Server started (Mini Api)'); var express = require('express'); var app = express(); var PORT = 3777; app.listen(PORT, function() { console.log("Port " + PORT + ": open.") }); app.get('/', function(request, response){ response.send("Bienvenido al mini api de saldos"); }); var bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({extended: true})); app.post('/postTest', function(request, response){ console.log(request.body); response.send("Gracias :D"); }); var pg = require('pg'); var URL = 'postgres://vxtorpoc:yHuj6XT90J-e5ZtMxj1tGUywFLcZb5IB@pellefant.db.elephantsql.com:5432/vxtorpoc'; var client = new pg.Client(URL); client.connect(function(err){ if(err){ return console.log('Error en la conexión a BD'); } console.log('Conexión exitosa'); client.end(); }); app.post('/api/insertar', function(req, res){ var cedula = req.body.id; var nombre = req.body.name; var dinero = req.body.cash; var queryInsertar = 'INSERT INTO saldos VALUES(' + cedula + ', ' + '\'' + nombre + '\', ' + dinero + ');' console.log(queryInsertar); pg.connect(URL, function(err, client, done){ if (err){ res.send('Error :('); return console.log('Error de conexión'); } client.query(queryInsertar, function(err, result){ if(err){ res.send('Error :('); client.end(); return console.log('Error en el query'); } console.log('Se insertó'); res.send('Ok :D'); client.end(); }); }); });//Funzione per effettuare le transizione window.addEventListener("beforeunload", function () { document.body.classList.remove("animte-in"); document.body.classList.add("animate-out"); });var cubism = exports.cubism = {version: "1.6.0"}; const baseURL = (repo) => `https://api.github.com/repos/amcmilne/${repo}`; export default baseURL;heresandyboy/mui-storyblok #!/usr/bin/env node require('dotenv').config(); const fs = require('fs'); const { exec } = require('child_process'); const files = fs.readdirSync('node_modules/mui-storyblok/dist/storyblok'); const fileNames = files.map(file => file.replace('.js', '')).filter(x => x != null).join(); const cmd = `npx storyblok-migrate --component-migrations --components ${fileNames}`; const asyncCmd = (command) => { console.log(command); return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { console.warn(error); reject(error); } console.log(stdout || stderr); resolve(stdout || stderr); }); }); }; const migrateComponents = async (command) => { process.chdir('./node_modules/mui-storyblok/dist'); await asyncCmd(command); }; migrateComponents(cmd); $(function() { const today = (new Date()).toISOString().substr(0, 10) firebase.initializeApp({ apiKey: '', authDomain: 'osta-ee.firebaseapp.com', databaseURL: 'https://osta-ee.firebaseio.com', projectId: 'osta-ee', storageBucket: '', messagingSenderId: '367995677054' }) // firebase.database().ref('auctions/').remove() firebase.database().ref('auctions/').orderByChild('updated').startAt(today).once('value').then(function (snapshot) { var limit = 120 var values = Object.values(snapshot.val()) var totalAuctions = values.length var skipedAuctions = 0 var deletedAuctions = 0 values.sort(function (a, b) { // if (a && a.id && a.id < b.id) { return 1 } // if (a && a.id && a.id > b.id) { return -1 } if (a && a.url && a.url.toLowerCase().trim() > b.url.toLowerCase().trim()) { return 1 } if (a && a.url && a.url.toLowerCase().trim() < b.url.toLowerCase().trim()) { return -1 } return 0 }) for (var i = 0; i < values.length; i++) { if (values[i].deleted) { deletedAuctions++ } else if ( values[i].url.toLowerCase().includes('-armeekaart-') || values[i].url.toLowerCase().includes('-entsuklopeedia-') || values[i].url.toLowerCase().includes('-eritempel-') || values[i].url.toLowerCase().includes('-etikett-') || values[i].url.toLowerCase().includes('-kangas-') || values[i].url.toLowerCase().includes('-kommipaber-') || values[i].url.toLowerCase().includes('-kop-') || values[i].url.toLowerCase().includes('-kopeek-') || values[i].url.toLowerCase().includes('-kopejka-') || values[i].url.toLowerCase().includes('-kopejki-') || values[i].url.toLowerCase().includes('-kopikas-') || values[i].url.toLowerCase().includes('-kopikat-') || values[i].url.toLowerCase().includes('-kunstsiid-') || values[i].url.toLowerCase().includes('-loteriipilet-') || values[i].url.toLowerCase().includes('-margialbum-') || values[i].url.toLowerCase().includes('-margid-') || values[i].url.toLowerCase().includes('-mark-') || values[i].url.toLowerCase().includes('-marki-') || values[i].url.toLowerCase().includes('-munt-') || values[i].url.toLowerCase().includes('-ollesilt-') || values[i].url.toLowerCase().includes('-pagunid-') || values[i].url.toLowerCase().includes('-postkaart-') || values[i].url.toLowerCase().includes('-rubl-') || values[i].url.toLowerCase().includes('-rubla-') || values[i].url.toLowerCase().includes('-silt-') || values[i].url.toLowerCase().includes('-sokolaadipaber-') || values[i].url.toLowerCase().includes('-taskukalender-') || values[i].url.toLowerCase().includes('-tass-') || values[i].url.toLowerCase().includes('-templiga-') || values[i].url.toLowerCase().includes('-umbrik-') || values[i].url.toLowerCase().includes('-umbrikud-') || values[i].url.toLowerCase().includes('-vimpel-') || values[i].url.toLowerCase().includes('/ensv-19') || values[i].url.toLowerCase().includes('/mark-') || values[i].url.toLowerCase().includes('/nouka-aegne-salajane-1') || values[i].url.toLowerCase().includes('/nsvl-19') || values[i].url.toLowerCase().includes('/tempel-') || values[i].url.toLowerCase().includes('/umbrik-') || values[i].url.toLowerCase().includes('/vimpel-') || values[i].url.toLowerCase().includes('jane-norman') || values[i].url.toLowerCase().includes('little-pony') || values[i].url.toLowerCase().includes('littlest-pet-shop') ) { skipedAuctions++ } else if (limit > 0) { limit-- var priceDisplay = (values[i].priceBuy || values[i].price || 0).toLocaleString('et', { style: 'currency', currency: 'EUR', currencyDisplay: 'symbol' }) $('#auctions').append('
' + priceDisplay + '' + values[i].title + '
') } $('h1').html('Total: ' + totalAuctions + '; Skiped: ' + skipedAuctions + '; Deleted: ' + deletedAuctions + '; ToDo: ' + (totalAuctions - (skipedAuctions + deletedAuctions))) } }) var updateAuctions = function (set) { var url = 'https://osta.ee/index.php?' var query = [ 'fuseaction=search.search', 'id=1000', 'limit=running', 'time=left', 'preset=', 'orderby=enda', 'gallery=', 'q[show_items]=1', 'q[type]=all', 'q[fuseaction]=search.search', 'q[searchform]=search.advanced', 'pagesize=180' ] var searches = [ [ {cat: 1000, q: 'nõuk' }, ], [ {cat: 1000, q: 'nsv' }, ], [ {cat: 723, q: 'eesti pop' }, {cat: 1000, q: 'cccp' }, {cat: 1000, q: 'cccr' }, {cat: 1000, q: 'dagö' }, {cat: 1000, q: 'diaposi' }, {cat: 1000, q: 'eesti kullafond cd' }, {cat: 1000, q: 'electronika' }, {cat: 1000, q: 'elektronika' }, {cat: 1000, q: 'gdr' }, {cat: 1000, q: 'jawa' }, {cat: 1000, q: 'juku' }, {cat: 1000, q: 'kala dvd' }, {cat: 1000, q: 'kalkulaator' }, {cat: 1000, q: 'konstruktor' }, {cat: 1000, q: 'lükati' }, {cat: 1000, q: 'majak' }, {cat: 1000, q: 'melodia' }, {cat: 1000, q: 'melodija' }, {cat: 1000, q: 'meloodia' }, {cat: 1000, q: 'muravei' }, {cat: 1000, q: 'norma' }, {cat: 1000, q: 'piko' }, {cat: 1000, q: 'radiotehnika' }, {cat: 1000, q: 'salvo' }, {cat: 1000, q: 'slaid' }, {cat: 1000, q: 'stopper' }, {cat: 1000, q: 'taskuarvut' }, {cat: 1000, q: 'ussr' }, {cat: 1000, q: 'vahvli' }, {cat: 1000, q: 'venea' }, {cat: 1000, q: 'vinüül' }, {cat: 1000, q: 'zenit' }, {cat: 1000, q: 'zx' }, {cat: 1000, q: 'маяк' }, {cat: 1000, q: 'ссср' }, {cat: 1000, seller: 'eller1' }, {cat: 1000, seller: 'FFMSRPDO' }, {cat: 1000, seller: 'hdrsport' }, {cat: 1000, seller: 'kuivik' }, {cat: 1000, seller: 'lugu' }, {cat: 1000, seller: 'maasees' }, // nostalgiapood {cat: 1000, seller: 'TigeSiil' }, {cat: 1000, seller: 'wallery' }, {cat: 1199 }, // mudelautod ], [ {cat: 2141 }, // nõukogudeaegsed kaubad ] ][set] var auctions = {} var auctionTotalCount = {} for (var s = 0; s < searches.length; s++) { var start = 0 var itemsCount = 1 while (itemsCount !== 0) { var fullUrl = url + query.join('&') + '&q[cat]=' + (searches[s].cat || '') + '&q[q]=' + (searches[s].q || '') + '&q[seller]=' + (searches[s].seller || '') + '&start=' + start $.ajax({ type: 'GET', url: fullUrl, async: false, success: function (data) { var html = $.parseHTML(data) var items = $(html).find('.main-content__section figure.offer-thumb') itemsCount = items.length start = start + itemsCount console.log('c:' + searches[s].cat + ' s:' + searches[s].seller + ' q:' + searches[s].q + ' - ' + start) for (var i = 0; i < items.length; i++) { var item = $(items[i]) var itemUrl = 'https://osta.ee/' + item.find('p.offer-thumb__title a').attr('href').replace('?_src=search', '') var id = parseInt(itemUrl.split('-').slice(-1)[0].split('.')[0]) var title = item.find('p.offer-thumb__title a').text().replace(/!/g , '').replace(/ /g , '').replace(/ /g , '').trim() var picture = item.find('img').data('original') var expires = item.find('li.offer-expires').text() || null var offers = parseInt(item.find('li.offers-made').text()) || null var price = parseFloat(item.find('span.price-cp').text().replace('€', '')) || null var priceBuy = parseFloat(item.find('span.price-bn').text().replace('€', '')) || null firebase.database().ref('auctions/' + id).update({ id: id, updated: (new Date()).toISOString(), title: title, url: itemUrl, picture: picture, expires: expires, offers: offers, price: price, priceBuy: priceBuy }) auctionTotalCount++ } $('h1').html('Updated: ' + auctionTotalCount) } }) } } } $('body').on('click', '.auction a', function (e) { if(!e.altKey) { return } $(this).parent().hide() firebase.database().ref('auctions/' + $(this).parent().data('id')).update({ deleted: (new Date()).toISOString() }) e.preventDefault() }) $('.updateAuctions').click(function () { updateAuctions($(this).data('set')) }) $('#deleteAllAuctions').click(function (e) { var count = $('.auction').length $('.auction').each(function () { count = count - 1 var item = $(this) firebase.database().ref('auctions/' + item.data('id')).update({ deleted: (new Date()).toISOString() }).then(function () { item.hide() if (count === 0) { setTimeout(function () { location.reload() }, 3000) } }) }) }) }) export { default, durationAsHms } from 'echo-ember-common/helpers/duration-as-hms' 1000+ import 'ratchet-npm/dist/css/ratchet.css'; // get ratchet import 'font-awesome/css/font-awesome.css'; // get font-awesome import 'animate.css/animate.css'; // get animate.css // import FastClick from 'fastclick'; import Vue from 'vue'; // get vue import VueProgressBar from 'vue-progressbar'; // get vue-progressbar import InfiniteScroll from 'vue-infinite-scroll'; // get vue-infinite-scroll import App from './app.vue'; // get root module import router from './router'; import store from './store'; // get vuex -> store // FastClick.attach(document.body); // init fastclick const options = { color: '#fff', failedColor: '#874b4b', thickness: '3px', transition: { speed: '0.2s', opacity: '0.6s' }, autoRevert: true, location: 'top', inverse: false }; Vue.use(VueProgressBar, options); Vue.use(InfiniteScroll); // init const app = new Vue({ router, store, render: h => h(App), }).$mount('#app'); import chai from 'chai'; import path from 'path'; import supertest from 'supertest'; import expressApiVersioning from '../index'; import versioningConfig from './config'; import app from './mock/server'; const request = supertest(app); const { expect } = chai; versioningConfig.apiPath = path.join(__dirname, './mock/api'); let newConfig; describe('Express API Versioning', () => { it('should throw an error when api path is not explicitly set', () => { newConfig = { ...versioningConfig, apiPath: '' }; expect(expressApiVersioning(newConfig, error => error.message)()) .to.equal('You must explicitly specify a path to where the APIs reside'); }); it('should throw an error when an instance of express is not set', () => { newConfig = { ...versioningConfig, instance: '' }; expect(expressApiVersioning(newConfig, error => error.message)()) .to.equal('You must explicitly set an instance of express'); }); it('should throw an error when api path cannot be found', () => { expect(expressApiVersioning( versioningConfig, error => error.message )({ url: '/api/v4' })) .to.equal('Entry point not Found'); }); it('should throw an error when an instance of express is not a function', () => { newConfig = { ...versioningConfig, instance: 'An instance' }; expect(expressApiVersioning(newConfig, error => error.message)()) .to.equal('An instance of express must be a function but got type string'); }); it('should throw an error if the endpoint does not match the test condition', () => { expect(expressApiVersioning(versioningConfig, error => error.message)({ url: '/api/unknown' })) .to.equal('No version number found'); }); it('should return 200 OK when the api route is found', (done) => { request .get('/api/v1/') .expect(200) .expect('Content-Type', /json/) .end((err, req) => { expect(JSON.parse(req.res.text).message).to.equal('Hello, you got to this end point successfully'); if (err) return done(err); done(); }); }); it('should return 200 OK when the client route is found', (done) => { request .get('/') .expect(200) .expect('Content-Type', /json/) .end((err, req) => { expect(JSON.parse(req.res.text).message).to.equal('You got to the client endpoint successfully'); if (err) return done(err); done(); }); }); }); const create = require('./create'); const find = require('./find'); const findAll = require('./findAll'); const findById = require('./findById'); const remove = require('./remove'); const update = require('./update'); module.exports = { create, find, findAll, findById, remove, update, }; import React, { Component } from 'react'; import { createMemoryHistory } from 'react-router-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'connected-react-router'; import { createHashHistory } from 'history'; import configureStore from './lib/configureStore'; import routes from './routes'; class ReactApp extends Component { render() { let isBrowser = typeof window === 'object'; let history = isBrowser ? createHashHistory() : createMemoryHistory('/'); let store = configureStore(history); return ( {routes} ); } } export default ReactApp; 0 import Kinetic from 'kinetic'; // Score rewarded for killing an enemy const ENEMY_VALUE = 500; // Score rewarded for collecting a coin const COIN_VALUE = 10; class ScoreManager { constructor() { this.score = 0; this.text = undefined; } drawScore(width) { var that = this; this.text = new Kinetic.Text({ text: 'Score: ' + that.score, fill: '#222', fontFamily: 'Helvetica', fontSize: 20, height: 25, width: 150, x: width - 150, y: 0 }); return that.text; } scoreCoin() { this.score += COIN_VALUE; console.log('+' + COIN_VALUE); } scoreEnemy() { this.score += ENEMY_VALUE; console.log('+' + ENEMY_VALUE + '!'); } updateScore() { this.text.setText('Score: ' + this.score); } } export default ScoreManager; 0 /* 品牌活动模块横向滚动 */ $(function(){ $("#jnBrandTab li a").click(function(){ $(this).parent().addClass("chos").siblings().removeClass("chos"); var idx = $("#jnBrandTab li a").index(this); showBrandList(idx); return false; }).eq(0).click(); }); //显示不同的模块 function showBrandList(index){ var $rollobj = $("#jnBrandList"); var rollWidth = $rollobj.find("li").outerWidth(); rollWidth = rollWidth * 4; //一个版面的宽度 $rollobj.stop(true,false).animate({ left : -rollWidth*index},1000); }opcaic/web-appapp/modules/admin/containers/layout/Sidebar/menuItems.js import { userRoleEnum } from '@/modules/shared/helpers/enumHelpers'; export const menuItems = [ { key: 'dashboard', link: '/admin', labelName: 'dashboard', requiredRole: userRoleEnum.ORGANIZER, }, { key: 'tournaments_list', link: '/admin/tournaments', labelName: 'tournaments', requiredRole: userRoleEnum.ORGANIZER, }, { key: 'games_list', link: '/admin/games', labelName: 'games', requiredRole: userRoleEnum.ORGANIZER, }, { key: 'users_list', link: '/admin/users', labelName: 'users', requiredRole: userRoleEnum.ADMIN, }, { key: 'email_templates', link: '/admin/emailTemplates', labelName: 'emailTemplates', requiredRole: userRoleEnum.ADMIN, }, { key: 'system', link: '/admin/system', labelName: 'system', requiredRole: userRoleEnum.ADMIN, }, ]; /* MIT License Copyright (c) 2022 KindCoder https://github.com/KindCoder-no/busstavla/blob/main/LICENSE */ // Include Packages var express = require('express') var router = express.Router() const fs = require('fs'); // Tavle router router.get('/', async function (req, res) { // Check if Tavla is installed if(process.env.INSTALLED === "TRUE"){ // If Tavla is install, render Tavla let raw_spotifydata = fs.readFileSync('./config.json'); let spotifydata = JSON.parse(raw_spotifydata); res.render('tavla', { access_token: spotifydata.spotify_access_token, tavle_name: process.env.TAVLE_NAME }); }else{ // If Tavla is not install, render welcome page res.render('welcome'); } }); // Export router module module.exports = router;1-10 import React, { Component } from 'react'; import styled from 'styled-components' import userProfile from '../../../../assets/Images/user-icon.png' import Dropdown from '../../../UI/Dropdown/Dropdown'; const StyledList = styled.li` img { height: 50px; width: 50px; } img:hover{ cursor: pointer; } ` class UserDropdown extends Component { constructor(props) { super(props); this.state = { visible: false } } toggleUserSettingsHandler = () => { this.setState(prevState => ({ visible: !prevState.visible })) } render() { return ( Home Settings ); } } export default UserDropdown;const fs = require('fs'); const path = require('path'); const config = require('config'); const mongoose = require('mongoose'); mongoose.Promise = global.Promise; const dbURL = `mongodb://${config.get('mongo.user')}:${config.get( 'mongo.password' )}@${config.get('mongo.host')}:${config.get('mongo.port')}/${config.get( 'mongo.db' )}`; let models = {}; const connection = mongoose.connect( dbURL, { useNewUrlParser: true } ); fs.readdirSync(__dirname + '/schemas') .filter(file => file.endsWith('.js')) .forEach(file => { console.log(file); var schema = require(path.join(__dirname + '/schemas/', file)); models[schema.name] = mongoose.model(schema.name, schema.schema); }); console.log('Loaded schemas...'); module.exports = { connection, models }; redeyecoding/dailyTodo const express = require('express'); const router = express.Router(); const auth = require('../../authMiddleware/auth'); const { check, validationResult } = require('express-validator'); const User = require('../../models/Users'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const tokenSecret = process.env.TOKEN_SECRET; const jwtExpress = require('express-jwt'); const { jwtConfig } = require('./utils'); router.get('/prodata',jwtExpress(jwtConfig), function(req, res){ res.send('your protect3ed data!!'); //Sets name = express }); // POST /api/auth // Login User // @ACcess router.post('/',[ check('email', 'Email address is required') .isEmail(), check('password', '') .not() .isEmpty() ], async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }) }; const { email, password } = req.body; try { // Check email const user = await User.findOne({ email: email }) if (!user) { return res.status(403).json({ errors: ['Invalid Credentials'] }) }; // Check password const validPassword = await bcrypt.compare(password, user.password); if (!validPassword) { return res.status(403).json({ errors: ['Invalid Credentials'] }) }; // setup Token // Assemble Token const payload = { user : { id: user.id } }; const token = jwt.sign({ data: payload }, tokenSecret); res.cookie('token',token , { maxAge:3600,httpOnly:true }); res.send('LOGGED IN') } catch(err) { console.error(err.message); console.log('TSTing123') res.status(500).send('Server Error') }; }); module.exports = router;MyApp.angular.constant('CFG', { push: { senderId: '888333666999' } }); //var csv is the CSV file with headers var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var xhr = new XMLHttpRequest(); fs = require("fs"); var csv = require('csv-parser'); const { Pool, Client } = require("pg"); let bookQueries = require("../book_sanctum/sqlQueries/bookQueries"); let bookQueryInstance = new bookQueries(); const pool = new Pool({ user: "apqsznwhludbct", host: "ec2-35-172-85-250.compute-1.amazonaws.com", database: "d66prsg7g28r53", password: "", port: "5432", ssl: true }); function readJSON(paths){ data = {}; for(let key in paths){ const currData = fs.readFileSync(paths[key]); data[key] = JSON.parse(currData.toString()); addDataDB(data,key); } } function addDataDB(data,key){ console.log(data[key]); switch(key){ case "book": addBookDB(data[key]); break; case "author": addAuthorDB(data[key]); break; case "genre": addGenreDB(data[key]); break; case "publisher": addPublisherDB(data[key]); } } function deleteData(){ pool.query('delete from book; delete from author; delete from genre; delete from publisher;', (err, result) => { if (err) { return console.error('Error executing query', err.stack) } //console.log(result.rows) // brianc }) } async function addBookDB(data){ for(let i =0; i4){ row["year"] = row.published_date.split('-')[0] } else{ row["year"] = row.published_date } //console.log(row.published_date) row.isbn13, row.title, row.description, row.author_id, row.genre_id, row.publisher_id, row.price, row.pages,row.year //console.log(row) a = await bookQueryInstance.addBook(row).then(function(result){ }); } } async function addGenreDB(data){ for(let i =0; isrc/components/Projects/styles.js import styled from "styled-components" import media from "../../styles/media" export const ItemContainerResponsive = styled.div` display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 1rem; grid-auto-rows: minmax(min-content, max-content); ${media.sm` display: none; `}; ` export const Title = styled.h3` text-align: center; ` export const ItemContainer = styled.div` display: none; ${media.sm` display: grid; grid-template-columns: repeat(4, 1fr); grid-gap: 1rem; grid-auto-rows: minmax(min-content, max-content); `}; ` export const Description = styled.p` text-align: justify; font-size: 0.75rem; ` clauderic/javascript foo || (foo = 'foobar'); foo.bar || (foo.bar = 'foobar'); foo.bar.baz || (foo.bar.baz = 'qux'); this.bar || (this.bar = 'foobar'); import * as types from './mutation-types' import {playMode} from 'assets/js/config' import {shuffle} from 'assets/js/util' import {saveSearch} from 'assets/js/cache' function findIndex(list, song) { return list.findIndex((item) => { return item.id === song.id }) } export const selectedPlay = function({commit, state}, {list, index}) { commit(types.SET_SEQUENCE_LIST, list) if (state.mode === playMode.random) { let randomList = shuffle(list) commit(types.SET_PLAYLIST, randomList) index = findIndex(randomList, list[index]) } else { commit(types.SET_PLAYLIST, list) } commit(types.SET_CURRENT_INDEX, index) commit(types.SET_FULL_SCREEN, true) commit(types.SET_PLAYING_STATE, true) } export const randomPlay = function ({commit}, {list}) { commit(types.SET_PLAY_MODE, playMode.random) commit(types.SET_SEQUENCE_LIST, list) let randomList = shuffle(list) commit(types.SET_PLAYLIST, randomList) commit(types.SET_CURRENT_INDEX, 0) commit(types.SET_FULL_SCREEN, true) commit(types.SET_PLAYING_STATE, true) } // 搜索结果列表的歌曲播放 export const searchPlay = function({commit, state}, song) { let playList = state.playList.slice() let seqList = state.sequenceList.slice() let currentIndex = state.currentIndex // 保存当前歌曲 let currentSong = playList[currentIndex] // !!! // splice() 方法 从数组中添加/删除项目,然后返回被删除的项目。 // 注释:该方法会改变原始数组。 // !!! // 【1】当前播放列表!!! // 试图在当前播放列表查找该歌曲(搜索结果的) let fIndex = findIndex(playList, song) // 插入当前播放列表 currentIndex++ playList.splice(currentIndex, 0, song) // 插入新歌曲后,须判断是否已经存在, if (fIndex > -1) { // 若存在,则删除原有歌曲!!! // 判断其插入的位置,在 当前播放歌曲的 前面 或者 后面 if (currentIndex > fIndex) { // 在前面 // 删除 playList.splice(fIndex, 1) // 因数组长度发生变化,当前播放索引减1 currentIndex-- } else { // 在后面 // 因为前面插入一个新的数据,所以之前查询到的数据的索引 需要加1 playList.splice(fIndex + 1, 1) } } // 【2】顺序播放列表!!! // 当前歌曲在 顺序播放列表中的索引 + 1 = 要插入的位置 let curSIndex = findIndex(seqList, currentSong) + 1 // 要插入的歌曲 是否存在 let fsIndex = findIndex(seqList, song) // 在当前歌曲之后,插入要插入的歌曲 seqList.splice(curSIndex, 0, song) if (fsIndex > -1) { if (curSIndex > fsIndex) { seqList.splice(fsIndex, 1) } else { seqList.splice(fsIndex + 1, 1) } } // 【3】提交修改、 commit(types.SET_PLAYLIST, playList) commit(types.SET_SEQUENCE_LIST, seqList) // commit(types.SET_PLAY_MODE, playMode.random) // let randomList = shuffle(list) commit(types.SET_CURRENT_INDEX, currentIndex) commit(types.SET_FULL_SCREEN, true) commit(types.SET_PLAYING_STATE, true) } // 保存搜索记录 export const saveSearchHistory = function ({commit}, query) { commit(types.SET_SEARCH_HISTORY, saveSearch(query)) }deepmacDetailCallback("84f883000000/24",[{"d":"2019-10-31","t":"add","s":"ieee-oui.csv","a":"12601 Research Pkwy Orlando FL US 32828-7335","c":"US","o":"Luminar Technologies"}]); /** * Query for diffDays * @param {Date} from_date - from date * @param {Date} to_date - to date * @returns {Number} */ const diffDays = (from_date, to_date) => { var diff = (new Date(to_date)).getTime() - (new Date(from_date)).getTime(); return Math.ceil(diff / (1000 * 3600 * 24) + 1); }; module.exports = { diffDays, }; 0 var Widget = { init: function(width,height){ this.width = width || 50; this.height = height || 50; this.$elem = null; }, insert: function($where){ if (this.$elem) { this.$elem.css({ width: this.width + "px", height: this.height + "px" }).appendTo($where); } } }; var Button = Object.create(Widget); Button.setup = function(width,height,label){ // delegated call this.init(width,height); this.label = label || "Default"; this.$elem = $("