code
stringlengths
2
1.05M
require("./subscribe.js"); require("./cdNav.js");
const fs = require('fs'); const argv = require('yargs').argv; /* * 3 args required: * --template: which file do we replace in? * --find: what string do we search for in the template? * --replace: what file do we replace the match with? */ const template = fs.readFileSync(argv.template).toString().trim(); //const replace = fs.readFileSync(argv.replace).toString(); let replace = fs.readFileSync('/dev/stdin').toString().trim(); if (argv.surround) { replace = argv.surround + replace + argv.surround; } const result = template.replace(argv.find, replace); console.log(result); //fs.writeFileSync(argv.template, result)
// node includes var zlib = require("zlib"); var EventEmitter = require("events"); var TelnetCommand = require("../telnet/Command"); var TelnetProtocol = require("../telnet/Protocol"); var TelnetEnvironment = require("../telnet/Environment"); // local includes var World; // convenience var xIAC = TelnetCommand.IAC.toString(16); var xWILL = TelnetCommand.WILL.toString(16); var xWONT = TelnetCommand.WONT.toString(16); var xDO = TelnetCommand.DO.toString(16); var xDONT = TelnetCommand.DONT.toString(16); var xSB = TelnetCommand.SB.toString(16); var xSE = TelnetCommand.SE.toString(16); /** * Client that handles socket for MUD. */ class MUDClient extends EventEmitter{ constructor(socket){ super(); /** * Incomplete transmissions from the client. * This usually means they're using an antiquated * telnet client that sends singular characters * immediately when typed. Can also be because * the client is sending IAC messages. * @type {String} */ this.incomplete = ""; /** * The socket we are managing. * @type {net.Socket} */ this.socket = socket; /** * @typedef MUDClient.TelnetSettings * @property {Array<Number, Number>} telnetSettings Telnet settings. */ /** * Telnet settings being tracked. * @type {MUDClient.TelnetSettings} */ this.telnetSettings = { protocol:[] }; /** * Should we deflate output? * @type {boolean} */ this.deflate = false; /** * zlib.Deflate stream for MCCP support. * @type {zlib.Deflate} */ this._deflater = null; /** * Fires when a MUDClient disconnects. * @event MUDClient#end */ socket.on("close", function(){ this.emit("close"); // propagate "end" event }.bind(this)); socket.on("data", function(data){ this.preprocess(data); }.bind(this)); // support ttype protocol this.DO(TelnetProtocol.TTYPE); } get socket(){ return this._socket; } set socket(socket){ this.address = socket.address(); socket.setEncoding("binary"); this._socket = socket; } /** * Returns a stringified version of the object. * @return {string} A string in the format of "MUDClient@&lt;address&gt;" */ toString(){ return `MUDClient@<${this.address.address}>`; } close(data){ if(data) { this.write(data, "utf8", function(){ this.socket.destroy(); }.bind(this)); } else this.socket.destroy(); } /** * Sends any data to the socket. * By default, it attempts to write all data encoded as binary. (ASCII) * If MCCP is enabled, this writes to the deflater instead. * @param {String} data Text to be sent to the client. */ send(data){ if(this.socket.destroyed) return; if(this.deflate) this._deflater.write(data, "binary"); else this.socket.write(data, "binary"); } /** * Shortcut to `this.send(data)`. * Appends a telnet linebreak. * @param {String} data Text to be sent to the client. */ sendLine(data){ this.send(data+"\r\n"); } /** * Parse telnet subnegotiation messages. * @param {String} data Data to parse. */ telnetSubNegotiation(data){ var protocol = data.charCodeAt(0); var command = data.charCodeAt(1); var etc = data.slice(1); var split = [TelnetProtocol.name(protocol)]; if(protocol == TelnetProtocol.TTYPE && data.charCodeAt(1) == TelnetEnvironment.IS){ var ttype = data.slice(2); this.telnetSettings.ttype = ttype; } } /** * Tell client we will use this protocol. * @param {TelnetProtocol} protocol Which protocol to handle. */ WILL(protocol){ this.send(String.fromCharCode(TelnetCommand.IAC, TelnetCommand.WILL, protocol)); } /** * Tell client we won't use this protocol. * @param {TelnetProtocol} protocol Which protocol to handle. */ WONT(protocol){ this.send(String.fromCharCode(TelnetCommand.IAC, TelnetCommand.WONT, protocol)); } /** * Tell the client to use this protocol. * @param {TelnetProtocol} protocol Which protocol to handle. */ DO(protocol){ this.send(String.fromCharCode(TelnetCommand.IAC, TelnetCommand.DO, protocol)); } /** * Tell the client not to use this protocol. * @param {TelnetProtocol} protocol Which protocol to handle. */ DONT(protocol){ this.send(String.fromCharCode(TelnetCommand.IAC, TelnetCommand.DONT, protocol)); } /** * Respond to WILL messages from client. * @param {TelnetProtocol} protocol Which protocol to handle. */ onWILL(protocol){ this.telnetSettings.protocol[protocol] = TelnetCommand.WILL; switch(protocol){ case TelnetProtocol.TTYPE: this.send(String.fromCharCode(TelnetCommand.IAC, TelnetCommand.SB, TelnetProtocol.TTYPE, TelnetEnvironment.SEND, TelnetCommand.IAC, TelnetCommand.SE)); break; default: // this.DONT(protocol); break; } } /** * Respond to WONT messages from client. * @param {TelnetProtocol} protocol Which protocol to handle. */ onWONT(protocol){ this.telnetSettings.protocol[protocol] = TelnetCommand.WONT; switch(protocol){ default: // this.DONT(protocol); break; } } /** * Respond to DO messages from client. * @param {TelnetProtocol} protocol Which protocol to handle. */ onDO(protocol){ this.telnetSettings.protocol[protocol] = TelnetCommand.DO; switch(protocol){ // start compressing output case TelnetProtocol.MCCP2: this.send(String.fromCharCode(TelnetCommand.IAC, TelnetCommand.SB, TelnetProtocol.MCCP2, TelnetCommand.IAC, TelnetCommand.SE)); this._deflater = zlib.createDeflate(); this._deflater.pipe(this._socket); this.deflate = true; break; default: // this.WONT(protocol); break; } } /** * Respond to DONT messages from client. * @param {TelnetProtocol} protocol Which protocol to handle. */ onDONT(protocol){ this.telnetSettings.protocol[protocol] = TelnetCommand.WONT; switch(protocol){ // stop compressing output case TelnetProtocol.MCCP2: this.deflate = false; this._deflater = null; default: // this.WONT(protocol); break; } } /** * Pre-process any input as necessary. * @param {String} data Text to process for later usage. */ preprocess(data){ // parse IAC codes directly from input before doing anything. var pos = data.indexOf(String.fromCharCode(TelnetCommand.IAC)); while(pos >= 0){ var next = data.charCodeAt(pos+1); var end = pos; switch(next){ // check for will/wont/do/dont case TelnetCommand.WILL: this.onWILL(data.charCodeAt(pos+2)); end+=3; break; case TelnetCommand.WONT: this.onWONT(data.charCodeAt(pos+2)); end+=3; break; case TelnetCommand.DO: this.onDO(data.charCodeAt(pos+2)); end+=3; break; case TelnetCommand.DONT: this.onDONT(data.charCodeAt(pos+2)); end+=3; break; // check for subnegotiations case TelnetCommand.SB: var end = data.indexOf(String.fromCharCode(TelnetCommand.IAC, TelnetCommand.SE), pos); if(end == -1) { World.log.error("Malformed telnet subnegotiation; no IAC SE.", data); break; } var n = data.slice(pos+2, end); this.telnetSubNegotiation(n); end += 3; break; } data = data.slice(0,pos) + data.slice(end); pos = data.indexOf(String.fromCharCode(TelnetCommand.IAC)); } if(data == "") return; var split = data.split("\r\n"); if(split.length == 1){ this.incomplete += split[0]; return; } if(this.incomplete){ split[0] = this.incomplete + split[0]; this.incomplete = ""; } if(split[split.length-1]=="") split.splice(split.length-1,1); for(var i=0;i<split.length;i++){ var line = split[i]; /** * Fires when the MUDClient sends valid text as input. * @event MUDClient#data * @param {String} line Line of text. */ this.emit("data", line); } } } module.exports = MUDClient; // cyclical includes World = require("../core/World");
function change_post_type(type){ $('#id_text').attr('placeholder',$('#type_'+type).attr('placeholder')); if (type == 1){ $('#new-quote-details').slideDown('slow'); }else{ $('#new-quote-details').slideUp('slow'); } $('.new-post-icon').each(function(index,value){ if (index==type){ $(this).attr('class','new-post-icon new-post-icon-active'); $('#post_form').attr('type',index); }else{ $(this).attr('class','new-post-icon'); } }) } $(document).ready(function() { $(document).pjax('[data-pjax]a, a[data-pjax]', '#pjax-container'); $(document).on('click', '.migrations-link', function() { $('.migrations').slideToggle(); if ($('.migrations-link').hasClass('migrations-link-inactive')) { $('.migrations-link').removeClass('migrations-link-inactive') .addClass('migrations-link-active'); } else { $('.migrations-link').removeClass('migrations-link-active') .addClass('migrations-link-inactive'); } }); $('#id_private_key').tooltip({ title: 'Private key is composed of 10 digits and characters, and is written in the book you received.', placement: 'bottom', trigger: 'focus', }); }); $(".deadline").children('a').bind("click", function () { span = $(this).parent().children('span'); span.slideToggle(5000); //span.slideToggle('slow'); }); function set_my_quote_callback(data){ if (data.done){ $.pnotify({ title: 'Profile Updated', text: data.message, opacity: .8 }) }else{ for (i in data.errors){ $.pnotify({ title: 'Error', type:'error', text: data.errors[i], opacity: .8 }) } } } function submit_private_key_callback(data){ if (data.done){ $.pnotify({ type: 'success', title: 'correct info', text: data.message, opacity: .8 }) }else{ for (i in data.errors){ $.pnotify({ title: 'Error', type:'error', text: data.errors[i], opacity: .8 }) } } } function left_nav_highlight(cls) { var cur_active = $('.left-nav li.active'); cur_active.children('a').append('<i class="icon-chevron-right pull-right"></i>'); cur_active.off('click'); cur_active.toggleClass('active'); var next_active = $('.left-nav .' + cls); next_active.toggleClass('active'); $('.icon-chevron-right', '.left-nav li.active').remove(); $('.left-nav li.active').click(function(e) { return false; }); } //TODO: It's very dirty code function close_1(){ $('#follow_suggestion_1').remove(); } function close_2(){ $('#follow_suggestion_2').remove(); } function close_3(){ $('#follow_suggestion_3').remove(); } function follow_request_callback_1(data){ alert(data.done); close_1(); } function follow_request_callback_2(data){ alert(data.done); close_2(); } function follow_request_callback_3(data){ alert(data.done); close_3(); }
angular.module('careWheels') //Notifications Component, as defined in design document. To be used to generate User Reminders and Red Alert tray notifications on Android. .factory("notifications", function($log, $cordovaLocalNotification){ var isAndroid = window.cordova!=undefined; //checks to see if cordova is available on this platform; platform() erroneously returns 'android' on Chrome Canary so it won't work var data; //needs to be called outside the functions so it persists for all of them var notifications = {}; notifications.getData = function(){ //console.log('hit getData'); //data = angular.fromJson(window.localStorage['Reminders']); //console.log('data:', data); return angular.fromJson(window.localStorage['Reminders']); }; notifications.Time = function() { this.hours=0; this.minutes=0; this.seconds=0; this.on=true; }; //To be called during app startup after login; retrieves saved alert times (if they exist) or creates default alerts (if they don't) //and calls Create_Notif for each of them notifications.Init_Notifs = function() { console.log('init notifs'); data = angular.fromJson(window.localStorage['Reminders']); console.log(data); if(data==null){ //have notifications been initialized before? //console.log("Initializing Notifications from default"); data = []; //data param needs to be initialized before indices can be added data[0] = new notifications.Time(); data[1] = new notifications.Time(); data[2] = new notifications.Time(); notifications.Create_Notif(10,0,0,true,1); //these correspond to the pre-chosen default alarm times notifications.Create_Notif(14,0,0,true,2); notifications.Create_Notif(19,0,0,true,3); } else { //need to check if each reminder, as any/all of them could be deleted by user //console.log("Initializing Notifications from memory"); notifications.Create_Notif(data[0].hours,data[0].minutes,data[0].seconds,data[0].on,1); notifications.Create_Notif(data[1].hours,data[1].minutes,data[1].seconds,data[1].on,2); notifications.Create_Notif(data[2].hours,data[2].minutes,data[2].seconds,data[2].on,3); } }; //Schedules a local notification and, if it is a reminder, saves a record of it to local storage. reminderNum must be <4 //or it will log an error and schedule no notifications. notifications.Create_Notif = function(hours, minutes, seconds, isOn, reminderNum){ if(reminderNum==0){ //is notif a red alert? if(isAndroid){ $cordovaLocalNotification.schedule({ //omitting 'at' and 'every' params means it occurs once, immediately id: reminderNum, message: "There are red alert(s) on your CareWheel!", title: "CareWheels", sound: null //should be updated to freeware sound }).then(function() { $log.log("Alert notification has been set"); }); } else $log.warn("Plugin disabled"); } if(reminderNum>0 && reminderNum <4){ //is notif a user reminder? var time = new Date(); //defaults to current date/time time.setHours(hours); //update data[reminderNum-1].hours = hours; time.setMinutes(minutes); data[reminderNum-1].minutes = minutes; time.setSeconds(seconds); data[reminderNum-1].seconds = seconds; data[reminderNum-1].on = isOn; window.localStorage['Reminders'] = angular.toJson(data); //save data so new reminder is stored if(isOn){ if(isAndroid){ $cordovaLocalNotification.schedule({ id: reminderNum, at: time, every: "day", text: "Reminder " + reminderNum + ": Please check in with your CareWheel!", title: "CareWheels", sound: null //same, hopefully a different sound than red alerts }).then(function() { $log.log("Notification" + reminderNum + "has been scheduled for " + time.toTimeString() + ", daily"); }); } else console.warn("Plugin disabled"); } else { //need to deschedule notification if it has been turned off if(isAndroid){ $cordovaLocalNotification.cancel(reminderNum, function() { console.log("Reminder" + reminderNum + " has been descheduled."); }); } } } else if(reminderNum >=4) $log.warn("Incorrect attempt to create notification for id #" + reminderNum); }; //Unschedules all local reminders; clears its index if it is a user reminder (id 1-3). notifications.Delete_Reminders = function(){ //NOTE: id corresponds to data array indices so it is off by one //data = angular.fromJson(window.localStorage['Reminders']); //console.log('hit delete reminders'); if(isAndroid){ for(i=1; i<4; ++i){ $cordovaLocalNotification.clear(i, function() { console.log(i + " is cleared"); }); } } else console.warn("Plugin disabled"); window.localStorage['Reminders'] = null; //and delete Reminders array data = null; }; /** * returns a reminder (id # = 0,1, or 2) as a string in the format HH:MM:SS * @return {string} */ notifications.Reminder_As_String = function(id){ if(id>2){ $log.error("Attempted to print Reminder id " + id + ", but there are only 3 reminders!"); } else { var hour = data[id].hours; if(hour<10) hour = 0 + String(hour); var minute = data[id].minutes; if(minute<10) minute = 0 + String(minute); //var second = data[id].minutes; //seconds can only be 00 currently //if(second<10) second = 0 + String(second); return hour + ":" + minute + ":00"; //+ second; } }; return notifications; });
import genMatrix from '../genMatrix' it('generates with ecl:M correctly', () => { const matrix = genMatrix('test') expect(matrix).toMatchSnapshot() }) it('generates with ecl:L correctly', () => { const matrix = genMatrix('test', 'L') expect(matrix).toMatchSnapshot() }) it('generates with ecl:H correctly', () => { const matrix = genMatrix('test', 'H') expect(matrix).toMatchSnapshot() }) it('generates with ecl:Q correctly', () => { const matrix = genMatrix('test', 'Q') expect(matrix).toMatchSnapshot() })
$(function(){ $(".detail-image").hide(); // ํ™”๋ฉด ํฌ๊ธฐ๋ฅผ ๋„˜์–ด๊ฐ€๋Š” ์ด๋ฏธ์ง€ ์‚ฌ์ด์ฆˆ ์žฌ์กฐ์ • (ํ™”๋ฉด์˜ 80%) setTimeout(function(){ if($(".detail-image").width() > window.innerWidth*0.8) { $(".detail-image").width(window.innerWidth*0.8); } $(".detail-image").show(); },100); // ๊ธ€ ์‚ญ์ œ $("#btn_delete").click(function(){ // ๊ธ€ ์‚ญ์ œ ํ™•์ธ if(confirm("๊ธ€์„ ์‚ญ์ œํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?")) { location.href="/index.php/freeboard/delete/"+$(this).attr("no"); } }); // ์ƒ์„ธ ์ด๋ฏธ์ง€ ํด๋ฆญ ํ›„ ํ™•๋Œ€ $(".detail-image").click(function(event){ // window.open($(this).attr("src")); event.preventDefault(); }); // ๊ธ€ ์ˆ˜์ • $("#btn-update").click(function(){ location.href = "/index.php/Freeboard/update_form/"+$(this).attr("no"); }); // ๋Œ“๊ธ€ ์“ฐ๊ธฐ ํ™œ์„ฑํ™” ๋ฒ„ํŠผ $(".btn-reply-go").click(function(){ $(".input-comm").focus(); }); $(".btn-good-area").click(function(){ if(confirm("์ด ๊ธ€์„ ์ถ”์ฒœํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?")) { $.ajax({ type: "POST", url: "/index.php/Freeboard/good", data: { wno: $("#wno").val() }, success: function(msg){ // console.log(msg); alert(msg); // alert("์„ฑ๊ณต"); }, error:function(request,status,error){ // alert("์‹คํŒจ"); alert(request.responseText); // alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error); if(!(request.responseText.includes("์ž๊ธฐ") || request.responseText.includes("์ด๋ฏธ"))) { $("#goods").text(parseInt($("#goods").text())+1); } }, dataType: "json" }); } }); // ๋Œ“๊ธ€ ์ƒˆ๋กœ๊ณ ์นจ $(".btn-reply-refresh").click(function(){ load_comment(); }); // ๋น„ํšŒ์›์ด ๋Œ“๊ธ€ ์ฐฝ ํ™œ์„ฑํ™” ์‹œ ์•Œ๋ฆผ ์ถœ๋ ฅ $("#inpt_comm").focus(function(){ if($("#is_login").val() != "Y") { alert("๋Œ“๊ธ€ ์ž‘์„ฑ์€ ๋กœ๊ทธ์ธ ํ›„ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."); $(this).blur(); } }); // ๋Œ“๊ธ€ ์ž‘์„ฑ $("#btn_submit").click(function(){ write_comment(); load_comment(); }); // ๋Œ“๊ธ€ ์‚ญ์ œ $("body").delegate(".btn-del-comm","click",function(){ if(confirm("๋Œ“๊ธ€์„ ์‚ญ์ œํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?")) { $.ajax({ type: "POST", url: "/index.php/comment/delete", data: { cno: $(this).attr("cno") }, success: function(msg){ alert(msg); }, error:function(request,status,error){ alert(request.responseText); // alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error); }, dataType: "json" }); load_comment(); } }); // ๋Œ“๊ธ€ ์ถ”์ฒœ $("body").delegate(".btn-goods","click",function(){ $.ajax({ type: "POST", url: "/index.php/comment/good", data: { cno: $(this).attr("cno") }, success: function(msg){ alert(msg); }, error:function(request,status,error){ alert(request.responseText); // alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error); }, dataType: "json" }); load_comment(); }); // ๋Œ“๊ธ€ ๋น„์ถ”์ฒœ $("body").delegate(".btn-bads","click",function(){ $.ajax({ type: "POST", url: "/index.php/comment/bad", data: { cno: $(this).attr("cno") }, success: function(msg){ alert(msg); }, error:function(request,status,error){ alert(request.responseText); // alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error); }, dataType: "json" }); load_comment(); }); load_comment(); }); // ๋Œ“๊ธ€ ์ถœ๋ ฅ function load_comment() { var resStr = ""; var wno = $("#wno").val(); $.getJSON("/index.php/comment/listMain/free/"+wno, function (json) { if(json.length == 0) { resStr += "<li>๋“ฑ๋ก๋œ ๋Œ“๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค.</li>"; } else { // ๋Œ“๊ธ€ ๊ฐฏ์ˆ˜ $("#comm_num").html("("+json.length+")"); } $.each(json, function (i, comm) { resStr += "<li>"; resStr += "<div>"; if(comm.l < 10) resStr += "<img src='/assets/img/level/lv0"+comm.l+".png'> "; else { resStr += "<img src='/assets/img/level/lv"+comm.l+".png'> "; } resStr += comm.n+" <font color='#aaa'>("+comm.rd+")</font>"; if($("#uno").val() == comm.uno) { resStr += "<span class='btn-del-comm' cno='"+comm.no+"'>x</span>"; } resStr += "</div>"; resStr += "<div>"; resStr += comm.c; resStr += "</div>"; resStr += "<div class='area-btn-comm'>"; resStr += "<button type='button' class='btn-reply' cno='"+comm.no+"'>๋‹ต๊ธ€</button>"; resStr += "<button type='button' class='btn-bads' cno='"+comm.no+"'>๋น„๊ณต๊ฐ"; if(comm.bads > 0) { resStr += comm.bads; } resStr += "</button>"; resStr += "<button type='button' class='btn-goods' cno='"+comm.no+"'>๊ณต๊ฐ"; if(comm.goods > 0) { resStr += comm.goods; } resStr += "</button>"; resStr += "</div>"; resStr += "</li>"; }); $("#ul_comm").empty(); $("#ul_comm").html(resStr); }); } // ๋Œ“๊ธ€ ๋“ฑ๋ก function write_comment() { if($.trim($("#inpt_comm").val()).length == 0) { alert("๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); $("#inpt_comm").focus(); return; } $.ajax({ type: "POST", url: "/index.php/comment/write", data: { // btype: $("#btype").val(), btype: "free", wno: $("#wno").val(), comment: $("#inpt_comm").val(), }, success: function(msg){ console.log(msg); }, dataType: "json" }); $("#inpt_comm").val(""); load_comment(); } function check_form(frm) { var title = frm.title.value; var comment = frm.comment.value; var image = frm.image.value; if($.trim(title).length == 0) { alert("์ œ๋ชฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); frm.title.focus(); return; } if($.trim(comment).length == 0) { alert("๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); frm.comment.focus(); return; } frm.submit(); } function onFileLoad(e) { $('#preview').prepend('<img style="width:50%;" src="'+e.target.result +'"/>'); $("#btn_image_del").show(); } function check_image(files) { if(files[0] == null) { return; } fileSize = Math.round(files[0].size/1024); // alert("File size is "+fileSize+" kb"); // 5MB ๋ณด๋‹ค ํด ๊ฒฝ์šฐ ๋“ฑ๋ก ์•ˆ๋˜๊ฒŒ if(fileSize > 5000) { alert("ํŒŒ์ผ์˜ ์šฉ๋Ÿ‰์ด ๋„ˆ๋ฌด ํฝ๋‹ˆ๋‹ค. ์ตœ๋Œ€ 5MB"); $("form input[type=file]").val(""); return; } var reader = new FileReader(); reader.onload = onFileLoad; reader.readAsDataURL(files[0]); }
function enableExitConfirmation(message) { if (typeof(message) === 'undefined') message = 'There are unsaved changes.'; $(window).bind('beforeunload', function(e) { return message; }); } function disableExitConfirmation() { $(window).unbind('beforeunload'); } function appendUrlParameter(url, key, value) { url = url.replace(new RegExp('[?&]' + key + '(=[^?&]+|(?!>[?&])|$)', 'g'), ''); var sep = url.indexOf('?') != - 1 ? '&' : '?'; url += sep; url += key; if (typeof(value) !== 'undefined') url += '=' + value; return url; } function sendAjax(url, data, successFunc, errorFunc) { var ajaxParams = { type: 'POST', url: url, data: data, }; if (data instanceof FormData) { ajaxParams.enctype = 'multipart/form-data'; ajaxParams.processData = false; ajaxParams.contentType = false; } $.ajax(ajaxParams).done(function(rawContent) { var content = $(rawContent); if (typeof(successFunc) !== 'undefined') successFunc(content); else window.location = content.filter('meta[data-current-url]').attr('data-current-url'); }).fail(function(xhr) { var content = $(xhr.responseText); if (typeof(errorFunc) !== 'undefined') errorFunc(content); else alert(content.find('.message').text()); }); } $(function() { $('body').on('submit', 'form', function(e) { e.preventDefault(); var form = $(this); var url = appendUrlParameter(form.attr('action'), 'simple'); var data = (typeof form.data('serializer') !== 'undefined') ? form.data('serializer')() : form.serialize(); var target = form.closest('.content-wrapper'); if (target.length == 0) target = form; var send = function() { sendAjax(url, data, form.data('success-callback'), form.data('error-callback')); } var messages = target.find('.message'); if (messages.length > 0) messages.slideUp().fadeOut('fast', send); else send(); }); }); function initGenericDragger(dragger, parentElement, dragStartCallback, dragMoveCallback, dragFinishCallback) { $(dragger).mousedown(function(e) { e.preventDefault(); var target = $(e.target).parents(parentElement); target.addClass('dragging'); target.data('changed', false); var internalDragMoveCallback = function(e) { dragMoveCallback(target, e); }; $('body') .addClass('dragging') .on('mousemove', target, internalDragMoveCallback) .one('mouseup', function(e) { e.preventDefault(); target.removeClass('dragging'); $('body').removeClass('dragging') $('body').off('mousemove', internalDragMoveCallback); if (typeof(dragFinishCallback) !== 'undefined') dragFinishCallback(target, target.data('changed')); }); if (typeof(dragStartCallback) !== 'undefined') dragStartCallback(target); }).click(function(e) { e.preventDefault(); }); } function moveDragHandler(target, e) { while (e.pageY < target.offset().top && target.prev().length > 0) { target.data('changed', true); target.insertBefore(target.prev()); } while (e.pageY > target.offset().top + target.height() && target.next().length > 0) { target.data('changed', true); target.insertAfter(target.next()); } } function initMoveDragger(dragger, parentElement, dragStartCallback, dragFinishCallback) { return initGenericDragger(dragger, parentElement, dragStartCallback, moveDragHandler, dragFinishCallback); }
๏ปฟ(function () { 'use strict'; angular .module('app') .service('msDate', msDate); function msDate() { return { from: from }; function from(date) { return '/Date(' + date.getTime() + '+0000)/'; } } })();
/** * Created by apache on 15-10-30. */ import alt from '../alt'; import SetActions from '../actions/SetActions'; class SetStore { constructor() { this.bindActions(SetActions); this.avatar_url = ''; this.username = ''; this.domain = ''; this.email = ''; this.account; this.intro = ''; this.github = 'javascript:;'; /* ่พ“ๅ…ฅๆฃ€ๆต‹ๆ—ถ่พ“ๅ‡บ็Šถๆ€ */ this.domainValidate = ''; this.nameValidate = ''; this.emailValidate = ''; this.introValidate = ''; } onChangeProfileSuccess(data) { if (data.code === 200) { toastr.success('ไฟฎๆ”น็”จๆˆท่ต„ๆ–™ๆˆๅŠŸ'); } else if(data.code === 500) { toastr.error('ๆœๅŠกๅ™จ้”™่ฏฏ'); } else { toastr.warning(data.meta); } } onChangeProfileFail() { toastr.error('ๆœๅŠกๅ™จ้”™่ฏฏ'); } onGetProfileSuccess(data) { if(data !== undefined && data.code === 200) { this.avatar_url = data.raw.avatar_url; this.username = data.raw.username; this.domain = data.raw.domain; this.email = data.raw.email; this.account = data.raw.account; this.intro = data.raw.introduce; this.github = data.raw.github || 'javascript:;'; } } onGetProfileLocal(data) { this.avatar_url = data.raw.avatar_url; this.username = data.raw.username; this.domain = data.raw.domain; this.email = data.raw.email; this.account = data.raw.account; this.intro = data.raw.introduce; this.github = data.raw.github || 'javascript:;'; } onProfileFail() { toastr.error('hehe'); } onChangeDomain(event) { this.domain = event.target.value; } onChangeEmail(event) { this.email = event.target.value; } onChangeUserName(event) { this.username = event.target.value; } onChangeIntro(event) { this.intro = event.target.value; } /** * @param option 1--error 0--not error */ onDomainValidateFail(option) { if(option === 1) { this.domainValidate = 'has-error'; } else if(option === 0) { this.domainValidate = ''; } } onNameValidateFail(option) { if(option === 1) { this.nameValidate = 'has-error'; } else if(option === 0) { this.nameValidate = ''; } } onEmailValidateFail(option) { if(option === 1) { this.emailValidate = 'has-error'; } else if(option === 0) { this.emailValidate = ''; } } onIntroValidateFail(option) { if(option === 1) { this.introValidate = 'has-error'; } else if(option === 0) { this.introValidate = ''; } } } export default alt.createStore(SetStore);
const amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost', (err, conn) => { conn.createChannel((err, ch) => { const q = 'task_queue'; const msg = process.argv.slice(2).join(' ') || 'Hello world'; ch.assertQueue(q, { durable: true }); ch.sendToQueue(q, Buffer.from(msg), { persistent: true }); console.log(' [x] Sent "hello world!"'); }); });
/*! * Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file. */ import {WebexPlugin} from '@webex/webex-core'; import querystring from 'querystring'; import {base64} from '@webex/common'; /** * @class * @extends {Lyra} * @memberof Lyra */ const Space = WebexPlugin.extend({ namespace: 'Lyra', /** * Lists lyra spaces associated with user * * @returns {Promise<Array>} spaces */ list() { return this.webex.request({ method: 'GET', api: 'lyra', resource: '/spaces' }) .then((res) => res.body.items); }, /** * Retrieves a lyra space info * @param {Types~LyraSpace} space * @param {string} space.id * @param {string} space.identity.id * @returns {Promise<LyraSpace>} response body */ get(space = {}) { const spaceId = space.id || space.identity && space.identity.id; if (!spaceId) { return Promise.reject(new Error('space.id is required')); } return this.webex.request({ method: 'GET', api: 'lyra', resource: `/spaces/${spaceId}` }) .then((res) => res.body); }, /** * Joins a lyra space, update every 10 minutes to keep alive for MANUAL * @param {Types~LyraSpace} space * @param {string} space.url * @param {object} options * @param {string} options.passType * @param {string} options.data additional data such as proof for ultrasound * @param {string} options.uri use a custom uri * @returns {Promise} */ join(space, options) { options = Object.assign({ passType: 'MANUAL' }, options); const body = { pass: { type: options.passType }, deviceUrl: this.webex.internal.device.url }; if (options.data) { body.pass.data = options.data; } if (options.verificationInitiation) { body.verificationInitiation = options.verificationInitiation; } // if options.uri is available use it, since that would have the // complete lyra service URL if (options.uri) { return this.webex.request({ method: 'PUT', uri: options.uri, body }); } return this.webex.request({ method: 'PUT', api: 'lyra', resource: `${space.url}/occupants/@me`, body }); }, /** * Leaves a lyra space * @param {Types~LyraSpace} space * @param {string} space.url * @param {object} options * @param {boolean} options.removeAllDevices remove all devices of current user also * @returns {Promise} */ leave(space, options = {}) { // all devices are removed by default (when deviceUrl is not supplied) let uri = `${space.url}/occupants/@me`; if (!options.removeAllDevices) { const params = { deviceUrl: base64.toBase64Url(this.webex.internal.device.url) }; uri += `?${querystring.stringify(params)}`; } return this.webex.request({ method: 'DELETE', api: 'lyra', resource: uri }); }, /** * Verifies a space occupant (to be used by the lyra device) * @param {Types~LyraSpace} space * @param {string} space.url * @param {string} occupantId id of user to verify * @returns {Promise} */ verifyOccupant(space, occupantId) { const body = { pass: { type: 'VERIFICATION' } }; return this.webex.request({ method: 'PUT', uri: `${space.url}/occupants/${occupantId}`, body }); }, /** * Gets the state of bindings in this Lyra space * @param {Types~LyraSpace} space * @param {string} space.url * @returns {Promise<LyraBindings>} bindings response body */ getCurrentBindings(space) { return this.webex.request({ method: 'GET', uri: `${space.url}/bindings` }) .then((res) => res.body); }, /** * Binds a conversation to lyra space * @param {Types~LyraSpace} space * @param {string} space.url * @param {string} space.id * @param {string} space.identity.id * @param {Types~Conversation} conversation * @param {string} conversation.kmsResourceObjectUrl * @param {string} conversation.url * @param {object} options * @param {boolean} options.uri complete lyra service URL * @returns {Promise<LyraBindings>} bindings response body */ bindConversation(space = {}, conversation = {}, options = {}) { const spaceId = space.id || space.identity && space.identity.id; if (!space.url) { return Promise.reject(new Error('space.url is required')); } if (!spaceId) { return Promise.reject(new Error('space.id is required')); } if (!conversation.kmsResourceObjectUrl) { return Promise.reject(new Error('conversation.kmsResourceObjectUrl is required')); } if (!conversation.url) { return Promise.reject(new Error('conversation.url is required')); } const body = { kmsMessage: { method: 'create', uri: '/authorizations', resourceUri: `${conversation.kmsResourceObjectUrl}`, userIds: [spaceId] }, conversationUrl: conversation.url }; const request = { method: 'POST', body }; // if options.uri is available use it, since that would have the // complete lyra service URL if (options.uri) { request.uri = options.uri; } else { request.api = 'lyra'; request.resource = `${space.url}/bindings`; } return this._bindConversation(spaceId) .then(() => this.webex.request(request)) .then((res) => res.body); }, /** * Binds a conversation to lyra space by posting capabilities to Lyra. * * Lyra no longer automatically enables binding for a space containing a device with type "SPARK_BOARD". * Webexboard now is running the CE code stack which supports posting of capabilities to Lyra. * @param {String} spaceId space ID * @returns {Promise<LyraBindings>} bindings response body */ _bindConversation(spaceId) { // Skip until we can bind a conversation to lyra space by posting capabilities to Lyra. /* eslint no-unreachable: 1 */ return Promise.resolve(); // PUT /lyra/api/v1/spaces/{spaceId}/devices/{encodedDeviceUrl}/capabilities const encodedDeviceUrl = base64.encode(this.webex.internal.device.url); const resource = `spaces/${spaceId}/devices/${encodedDeviceUrl}/capabilities`; return this.webex.request({ method: 'PUT', api: 'lyra', resource, body: { bindingCleanupAfterCall: true } }); }, /** * Removes binding between a conversation and a lyra space using conversation * url * @param {Types~LyraSpace} space * @param {string} space.url * @param {string} space.id * @param {string} space.identity.id * @param {Types~Conversation} conversation * @param {string} conversation.kmsResourceObjectUrl * @param {string} conversation.url * @param {object} options * @param {boolean} options.uri complete lyra service URL * @returns {Promise<LyraBindings>} bindings response body */ unbindConversation(space = {}, conversation = {}, options = {}) { const spaceId = space.id || space.identity && space.identity.id; if (!space.url) { return Promise.reject(new Error('space.url is required')); } if (!spaceId) { return Promise.reject(new Error('space.id is required')); } if (!conversation.url) { return Promise.reject(new Error('conversation.url is required')); } if (!conversation.kmsResourceObjectUrl) { return Promise.reject(new Error('conversation.kmsResourceObjectUrl is required')); } const parameters = { kmsMessage: { method: 'delete', uri: `${conversation.kmsResourceObjectUrl}/authorizations?${querystring.stringify({authId: spaceId})}` }, conversationUrl: base64.toBase64Url(conversation.url) }; return this.webex.internal.encryption.kms.prepareRequest(parameters.kmsMessage) .then((req) => { parameters.kmsMessage = req.wrapped; // if options.uri is available use it, since that would have the // complete lyra service URL if (options.uri) { return this.webex.request({ method: 'DELETE', uri: `${options.uri}?${querystring.stringify(parameters)}` }); } return this.webex.request({ method: 'DELETE', api: 'lyra', resource: `${space.url}/bindings?${querystring.stringify(parameters)}` }); }); }, /** * Delete a binding using binding id * @param {Types~LyraSpace} space * @param {string} space.url * @param {string} space.identity.id * @param {object} options * @param {string} options.kmsResourceObjectUrl * @param {string} options.bindingId * @returns {Promise<LyraBindings>} bindings response body */ deleteBinding(space = {}, options = {}) { const spaceId = space.id || space.identity && space.identity.id; if (!space.url) { return Promise.reject(new Error('space.url is required')); } if (!spaceId) { return Promise.reject(new Error('space.id is required')); } if (!options.kmsResourceObjectUrl) { return Promise.reject(new Error('options.kmsResourceObjectUrl is required')); } if (!options.bindingId) { return Promise.reject(new Error('options.bindingId is required')); } const parameters = { kmsMessage: { method: 'delete', uri: `${options.kmsResourceObjectUrl}/authorizations?${querystring.stringify({authId: spaceId})}` } }; return this.webex.internal.encryption.kms.prepareRequest(parameters.kmsMessage) .then((req) => { parameters.kmsMessage = req.wrapped; return this.webex.request({ method: 'DELETE', uri: `${space.url}/bindings/${options.bindingId}?${querystring.stringify(parameters)}` }); }); } }); export default Space;
(function () { 'use strict'; // create application... // this doesn't do anything here angular.module('ngSpRestApi', []); })();
window.categorizedFunctionInfo = function() { return ( { "Arithmetic Functions":{ "abs":{ "name":"abs", "displayName":"abs", "category":"Arithmetic Functions", "description":"Returns the absolute value of its numeric argument.", "minArgs":1, "maxArgs":1, "args":[ { "name":"number", "type":"number", "description":"a numeric value", "required":true } ], "examples":[ "abs(-1) returns 1", "abs(speed) returns 10 when speed is -10 or 10" ] }, "ceil":{ "name":"ceil", "displayName":"ceil", "category":"Arithmetic Functions", "description":"Returns the smallest integer greater than or equal to its numeric argument.", "minArgs":1, "maxArgs":1, "args":[ { "name":"number", "type":"number", "description":"a numeric value", "required":true } ], "examples":[ "ceil(1) returns 1", "ceil(1.5) returns 2", "ceil(-1.5) returns -1" ] }, "exp":{ "name":"exp", "displayName":"exp", "category":"Arithmetic Functions", "description":"Returns the result of computing the constant e to the power of its numeric argument.", "minArgs":1, "maxArgs":1, "args":[ { "name":"number", "type":"number", "description":"a numeric value", "required":true } ], "examples":[ ] }, "floor":{ "name":"floor", "displayName":"floor", "category":"Arithmetic Functions", "description":"Returns the largest integer less than or equal to its numeric argument.", "minArgs":1, "maxArgs":1, "args":[ { "name":"number", "type":"number", "description":"a numeric value", "required":true } ], "examples":[ "floor(1) returns 1", "floor(1.5) returns 1", "floor(-1.5) returns -2" ] }, "pow":{ "name":"pow", "displayName":"pow", "category":"Arithmetic Functions", "description":"", "minArgs":2, "maxArgs":2, "examples":[ ] }, "sqrt":{ "name":"sqrt", "displayName":"sqrt", "category":"Arithmetic Functions", "description":"", "minArgs":1, "maxArgs":1, "examples":[ ] }, "frac":{ "name":"frac", "displayName":"frac", "category":"Arithmetic Functions", "description":"", "minArgs":1, "maxArgs":1, "examples":[ ] }, "ln":{ "name":"ln", "displayName":"ln", "category":"Arithmetic Functions", "description":"", "minArgs":1, "maxArgs":1, "examples":[ ] }, "log":{ "name":"log", "displayName":"log", "category":"Arithmetic Functions", "description":"", "minArgs":1, "maxArgs":1, "examples":[ ] }, "round":{ "name":"round", "displayName":"round", "category":"Arithmetic Functions", "description":"", "minArgs":1, "maxArgs":2, "examples":[ ] }, "trunc":{ "name":"trunc", "displayName":"trunc", "category":"Arithmetic Functions", "description":"", "minArgs":1, "maxArgs":1, "examples":[ ] } }, "Trigonometric Functions":{ "acos":{ "name":"acos", "displayName":"acos", "category":"Trigonometric Functions", "minArgs":1, "maxArgs":1 }, "asin":{ "name":"asin", "displayName":"asin", "category":"Trigonometric Functions", "minArgs":1, "maxArgs":1 }, "atan":{ "name":"atan", "displayName":"atan", "category":"Trigonometric Functions", "minArgs":1, "maxArgs":1 }, "atan2":{ "name":"atan2", "displayName":"atan2", "category":"Trigonometric Functions", "minArgs":2, "maxArgs":2 }, "cos":{ "name":"cos", "displayName":"cos", "category":"Trigonometric Functions", "minArgs":1, "maxArgs":1 }, "sin":{ "name":"sin", "displayName":"sin", "category":"Trigonometric Functions", "minArgs":1, "maxArgs":1 }, "tan":{ "name":"tan", "displayName":"tan", "category":"Trigonometric Functions", "minArgs":1, "maxArgs":1 } }, "Other Functions":{ "boolean":{ "name":"boolean", "displayName":"boolean", "category":"Other Functions", "minArgs":1, "maxArgs":1 }, "if":{ "name":"if", "displayName":"if", "category":"Other Functions", "minArgs":2, "maxArgs":3 }, "isFinite":{ "name":"isFinite", "displayName":"isFinite", "category":"Other Functions", "minArgs":1, "maxArgs":1 }, "number":{ "name":"number", "displayName":"number", "category":"Other Functions", "minArgs":1, "maxArgs":1 }, "random":{ "name":"random", "displayName":"random", "category":"Other Functions", "minArgs":0, "maxArgs":2 }, "string":{ "name":"string", "displayName":"string", "category":"Other Functions", "minArgs":1, "maxArgs":1 }, "greatCircleDistance":{ "name":"greatCircleDistance", "displayName":"greatCircleDistance", "category":"Other Functions", "minArgs":4, "maxArgs":4 } }, "Lookup Functions":{ "lookupByIndex":{ "name":"lookupByIndex", "displayName":"lookupByIndex", "category":"Lookup Functions", "minArgs":3, "maxArgs":3 }, "lookupByKey":{ "name":"lookupByKey", "displayName":"lookupByKey", "category":"Lookup Functions", "minArgs":4, "maxArgs":4 }, "first":{ "name":"first", "displayName":"first", "category":"Lookup Functions", "minArgs":1, "maxArgs":2 }, "last":{ "name":"last", "displayName":"last", "category":"Lookup Functions", "minArgs":1, "maxArgs":2 }, "next":{ "name":"next", "displayName":"next", "category":"Lookup Functions", "minArgs":1, "maxArgs":3 }, "prev":{ "name":"prev", "displayName":"prev", "category":"Lookup Functions", "minArgs":1, "maxArgs":3 } }, "Date/Time Functions":{ "date":{ "name":"date", "displayName":"date", "category":"Date/Time Functions", "description":"", "minArgs":1, "maxArgs":7, "examples":[ ] }, "dayOfMonth":{ "name":"dayOfMonth", "displayName":"dayOfMonth", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "dayOfWeek":{ "name":"dayOfWeek", "displayName":"dayOfWeek", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "dayOfWeekName":{ "name":"dayOfWeekName", "displayName":"dayOfWeekName", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "hours":{ "name":"hours", "displayName":"hours", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "minutes":{ "name":"minutes", "displayName":"minutes", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "month":{ "name":"month", "displayName":"month", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "monthName":{ "name":"monthName", "displayName":"monthName", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "now":{ "name":"now", "displayName":"now", "category":"Date/Time Functions", "minArgs":0, "maxArgs":0 }, "seconds":{ "name":"seconds", "displayName":"seconds", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 }, "today":{ "name":"today", "displayName":"today", "category":"Date/Time Functions", "minArgs":0, "maxArgs":0 }, "year":{ "name":"year", "displayName":"year", "category":"Date/Time Functions", "minArgs":1, "maxArgs":1 } }, "String Functions":{ "beginsWith":{ "name":"beginsWith", "displayName":"beginsWith", "category":"String Functions", "minArgs":2, "maxArgs":2 }, "charAt":{ "name":"charAt", "displayName":"charAt", "category":"String Functions", "minArgs":1, "maxArgs":1 }, "concat":{ "name":"concat", "displayName":"concat", "category":"String Functions", "minArgs":1, "maxArgs":99 }, "endsWith":{ "name":"endsWith", "displayName":"endsWith", "category":"String Functions", "minArgs":2, "maxArgs":2 }, "findString":{ "name":"findString", "displayName":"findString", "category":"String Functions", "minArgs":2, "maxArgs":3 }, "patternMatches":{ "name":"patternMatches", "displayName":"patternMatches", "category":"String Functions", "minArgs":2, "maxArgs":2 }, "includes":{ "name":"includes", "displayName":"includes", "category":"String Functions", "minArgs":2, "maxArgs":2 }, "join":{ "name":"join", "displayName":"join", "category":"String Functions", "minArgs":1, "maxArgs":99 }, "repeatString":{ "name":"repeatString", "displayName":"repeatString", "category":"String Functions", "minArgs":2, "maxArgs":2 }, "replaceChars":{ "name":"replaceChars", "displayName":"replaceChars", "category":"String Functions", "minArgs":4, "maxArgs":4 }, "replaceString":{ "name":"replaceString", "displayName":"replaceString", "category":"String Functions", "minArgs":3, "maxArgs":3 }, "split":{ "name":"split", "displayName":"split", "category":"String Functions", "minArgs":2, "maxArgs":3 }, "subString":{ "name":"subString", "displayName":"subString", "category":"String Functions", "minArgs":2, "maxArgs":3 }, "stringLength":{ "name":"stringLength", "displayName":"stringLength", "category":"String Functions", "minArgs":1, "maxArgs":1 }, "toLower":{ "name":"toLower", "displayName":"toLower", "category":"String Functions", "minArgs":1, "maxArgs":1 }, "toUpper":{ "name":"toUpper", "displayName":"toUpper", "category":"String Functions", "minArgs":1, "maxArgs":1 }, "trim":{ "name":"trim", "displayName":"trim", "category":"String Functions", "minArgs":1, "maxArgs":1 } }, "Statistical Functions":{ "count":{ "name":"count", "displayName":"count", "category":"Statistical Functions", "description":"Returns the number of cases with non-empty/non-false values for its expression argument.", "minArgs":0, "maxArgs":1, "args":[ { "name":"expression", "type":"any", "description":"The values to be counted." }, { "name":"filter", "type":"boolean", "description":"An expression that determines the cases to be considered." } ], "examples":[ "count() with no arguments is interpreted differently depending on the context. In an attribute formula it returns the number of child cases. In a plotted value, it is equivalent to count(xAxisAttribute).", "count(height) returns 3 if the 'height' attribute contains [1, \"yes\", true, false, \"\"].", "count(height, age<18) returns 3 if the 'height' attribute contains [1, \"yes\", true, false, \"\"] for the cases with a value for the age attribute that is less than 18." ] }, "min":{ "name":"min", "displayName":"min", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 }, "max":{ "name":"max", "displayName":"max", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 }, "mean":{ "name":"mean", "displayName":"mean", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 }, "median":{ "name":"median", "displayName":"median", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 }, "variance":{ "name":"variance", "displayName":"variance", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 }, "stdDev":{ "name":"stdDev", "displayName":"stdDev", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 }, "stdErr":{ "name":"stdErr", "displayName":"stdErr", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 }, "percentile":{ "name":"percentile", "displayName":"percentile", "category":"Statistical Functions", "minArgs":2, "maxArgs":2 }, "sum":{ "name":"sum", "displayName":"sum", "category":"Statistical Functions", "minArgs":1, "maxArgs":1 } } } ); };
// default samples // /_design/default/_view/samples function(doc) { for each(sample in doc.HEADER.samples){ emit(doc._id, sample); } }
/** * @license simple-loop https://github.com/flams/simple-loop * * The MIT License (MIT) * * Copyright (c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com> */ "use strict"; function assert(assertion, error) { if (assertion) { throw new TypeError("simple-loop: " + error); } } /** * Small abstraction for looping over objects and arrays * Warning: it's not meant to be used with nodeList * To use with nodeList, convert to array first * @param {Array/Object} iterated the array or object to loop through * @param {Function} callback the function to execute for each iteration * @param {Object} scope the scope in which to execute the callback */ module.exports = function loop(iterated, callback, scope) { assert(typeof iterated != "object", "iterated must be an array/object"); assert(typeof callback != "function", "callback must be a function"); var i; if (Array.isArray(iterated)) { for (i = 0; i < iterated.length; i++) { callback.call(scope, iterated[i], i, iterated); } } else { for (i in iterated) { if (iterated.hasOwnProperty(i)) { callback.call(scope, iterated[i], i, iterated); } } } };
import React from 'react' import { MarkersInfoContainer } from '../../App/Containers/MainView/BottomSheet/MarkersInfo/MarkersInfoContainer' import renderer from 'react-test-renderer' test('MarkersInfoContainer renders correctly', () => { const tree = renderer.create( <MarkersInfoContainer setMarkerSelected={() => {}} setMarkerViewVisible={() => {}} disableGestures={() => {}} markerList = {[{latitude: 1, longitude: 1, title: "", text: ""}]} /> ).toJSON(); expect(tree).toMatchSnapshot(); });
#!/usr/bin/env node --harmony_destructuring // #!/usr/local/bin/node --harmony_destructuring var input = process.argv[2] || "2-3-4"; var PEG = require("./simple.js"); var r = PEG.parse(input); console.log(`result = ${r}`);
import React from 'react'; import ReactDOM from 'react-dom'; import BirthdayParty from './src'; document.addEventListener('DOMContentLoaded', () => { ReactDOM.render( <div><BirthdayParty/></div>, document.getElementById('birthday-party') ); });
var simplesudoku = require('..'), assert = require('assert'); // Load empty board from string var game = simplesudoku.createGame(); game.load(".........."); var positions = game.getNumberPositions(); assert.ok(positions); assert.equal(positions.length, 0); // Load first row from string var game = simplesudoku.createGame(); game.load("123456789"); var positions = game.getNumberPositions(); assert.ok(positions); assert.equal(positions.length, 9); for (var k = 0; k < 9; k++) { var position = positions[k]; assert.equal(position.y, 0); assert.equal(position.x, k); assert.equal(position.number, k + 1); } // Load second row from string var game = simplesudoku.createGame(); game.load(".........123456789"); var positions = game.getNumberPositions(); assert.ok(positions); assert.equal(positions.length, 9); for (var k = 0; k < 9; k++) { var position = positions[k]; assert.equal(position.y, 1); assert.equal(position.x, k); assert.equal(position.number, k + 1); } // Load third row from string, with spaces and new lines var game = simplesudoku.createGame(); game.load(". . . . . . . . .\n. . . . . . . . .\n1 2 3 4 5 6 7 8 9"); var positions = game.getNumberPositions(); assert.ok(positions); assert.equal(positions.length, 9); for (var k = 0; k < 9; k++) { var position = positions[k]; assert.equal(position.y, 2); assert.equal(position.x, k); assert.equal(position.number, k + 1); }
export const googlePlus3 = {"viewBox":"0 0 16 16","children":[{"name":"path","attribs":{"fill":"#000000","d":"M8 0c-4.419 0-8 3.581-8 8s3.581 8 8 8 8-3.581 8-8-3.581-8-8-8zM6 12c-2.212 0-4-1.787-4-4s1.788-4 4-4c1.081 0 1.984 0.394 2.681 1.047l-1.088 1.044c-0.297-0.284-0.816-0.616-1.594-0.616-1.366 0-2.481 1.131-2.481 2.525s1.116 2.525 2.481 2.525c1.584 0 2.178-1.137 2.269-1.725h-2.269v-1.372h3.778c0.034 0.2 0.063 0.4 0.063 0.663 0 2.287-1.531 3.909-3.841 3.909zM13 8v1h-1v-1h-1v-1h1v-1h1v1h1v1h-1z"}}]};
(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); }; } function installSetTimeoutImplementation() { registerImmediate = function(handle) { setTimeout(runIfPresent, 0, handle); }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6โ€“8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self)); /******************************************************************************* * Copyright (c) 2013 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Andrew Banks - initial API and implementation and initial documentation *******************************************************************************/ // Only expose a single object name in the global namespace. // Everything must go through this module. Global Paho.MQTT module // only has a single public function, client, which returns // a Paho.MQTT client object given connection details. /** * Send and receive messages using web browsers. * <p> * This programming interface lets a JavaScript client application use the MQTT V3.1 or * V3.1.1 protocol to connect to an MQTT-supporting messaging server. * * The function supported includes: * <ol> * <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number. * <li>Specifying options that relate to the communications link with the server, * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required. * <li>Subscribing to and receiving messages from MQTT Topics. * <li>Publishing messages to MQTT Topics. * </ol> * <p> * The API consists of two main objects: * <dl> * <dt><b>{@link Paho.MQTT.Client}</b></dt> * <dd>This contains methods that provide the functionality of the API, * including provision of callbacks that notify the application when a message * arrives from or is delivered to the messaging server, * or when the status of its connection to the messaging server changes.</dd> * <dt><b>{@link Paho.MQTT.Message}</b></dt> * <dd>This encapsulates the payload of the message along with various attributes * associated with its delivery, in particular the destination to which it has * been (or is about to be) sent.</dd> * </dl> * <p> * The programming interface validates parameters passed to it, and will throw * an Error containing an error message intended for developer use, if it detects * an error with any parameter. * <p> * Example: * * <code><pre> client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId"); client.onConnectionLost = onConnectionLost; client.onMessageArrived = onMessageArrived; client.connect({onSuccess:onConnect}); function onConnect() { // Once a connection has been made, make a subscription and send a message. console.log("onConnect"); client.subscribe("/World"); message = new Paho.MQTT.Message("Hello"); message.destinationName = "/World"; client.send(message); }; function onConnectionLost(responseObject) { if (responseObject.errorCode !== 0) console.log("onConnectionLost:"+responseObject.errorMessage); }; function onMessageArrived(message) { console.log("onMessageArrived:"+message.payloadString); client.disconnect(); }; * </pre></code> * @namespace Paho.MQTT */ if (typeof Paho === "undefined") { Paho = {}; } Paho.MQTT = (function (global) { // Private variables below, these are only visible inside the function closure // which is used to define the module. var version = "@VERSION@"; var buildLevel = "@BUILDLEVEL@"; /** * Unique message type identifiers, with associated * associated integer values. * @private */ var MESSAGE_TYPE = { CONNECT: 1, CONNACK: 2, PUBLISH: 3, PUBACK: 4, PUBREC: 5, PUBREL: 6, PUBCOMP: 7, SUBSCRIBE: 8, SUBACK: 9, UNSUBSCRIBE: 10, UNSUBACK: 11, PINGREQ: 12, PINGRESP: 13, DISCONNECT: 14 }; // Collection of utility methods used to simplify module code // and promote the DRY pattern. /** * Validate an object's parameter names to ensure they * match a list of expected variables name for this option * type. Used to ensure option object passed into the API don't * contain erroneous parameters. * @param {Object} obj - User options object * @param {Object} keys - valid keys and types that may exist in obj. * @throws {Error} Invalid option parameter found. * @private */ var validate = function(obj, keys) { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (keys.hasOwnProperty(key)) { if (typeof obj[key] !== keys[key]) throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key])); } else { var errorStr = "Unknown property, " + key + ". Valid properties are:"; for (var key in keys) if (keys.hasOwnProperty(key)) errorStr = errorStr+" "+key; throw new Error(errorStr); } } } }; /** * Return a new function which runs the user function bound * to a fixed scope. * @param {function} User function * @param {object} Function scope * @return {function} User function bound to another scope * @private */ var scope = function (f, scope) { return function () { return f.apply(scope, arguments); }; }; /** * Unique message type identifiers, with associated * associated integer values. * @private */ var ERROR = { OK: {code:0, text:"AMQJSC0000I OK."}, CONNECT_TIMEOUT: {code:1, text:"AMQJSC0001E Connect timed out."}, SUBSCRIBE_TIMEOUT: {code:2, text:"AMQJS0002E Subscribe timed out."}, UNSUBSCRIBE_TIMEOUT: {code:3, text:"AMQJS0003E Unsubscribe timed out."}, PING_TIMEOUT: {code:4, text:"AMQJS0004E Ping timed out."}, INTERNAL_ERROR: {code:5, text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"}, CONNACK_RETURNCODE: {code:6, text:"AMQJS0006E Bad Connack return code:{0} {1}."}, SOCKET_ERROR: {code:7, text:"AMQJS0007E Socket error:{0}."}, SOCKET_CLOSE: {code:8, text:"AMQJS0008I Socket closed."}, MALFORMED_UTF: {code:9, text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."}, UNSUPPORTED: {code:10, text:"AMQJS0010E {0} is not supported by this browser."}, INVALID_STATE: {code:11, text:"AMQJS0011E Invalid state {0}."}, INVALID_TYPE: {code:12, text:"AMQJS0012E Invalid type {0} for {1}."}, INVALID_ARGUMENT: {code:13, text:"AMQJS0013E Invalid argument {0} for {1}."}, UNSUPPORTED_OPERATION: {code:14, text:"AMQJS0014E Unsupported operation."}, INVALID_STORED_DATA: {code:15, text:"AMQJS0015E Invalid data in local storage key={0} value={1}."}, INVALID_MQTT_MESSAGE_TYPE: {code:16, text:"AMQJS0016E Invalid MQTT message type {0}."}, MALFORMED_UNICODE: {code:17, text:"AMQJS0017E Malformed Unicode string:{0} {1}."}, BUFFER_FULL: {code:18, text:"AMQJS0018E Message buffer is full, maximum buffer size: ${0}."}, }; /** CONNACK RC Meaning. */ var CONNACK_RC = { 0:"Connection Accepted", 1:"Connection Refused: unacceptable protocol version", 2:"Connection Refused: identifier rejected", 3:"Connection Refused: server unavailable", 4:"Connection Refused: bad user name or password", 5:"Connection Refused: not authorized" }; /** * Format an error message text. * @private * @param {error} ERROR.KEY value above. * @param {substitutions} [array] substituted into the text. * @return the text with the substitutions made. */ var format = function(error, substitutions) { var text = error.text; if (substitutions) { var field,start; for (var i=0; i<substitutions.length; i++) { field = "{"+i+"}"; start = text.indexOf(field); if(start > 0) { var part1 = text.substring(0,start); var part2 = text.substring(start+field.length); text = part1+substitutions[i]+part2; } } } return text; }; //MQTT protocol and version 6 M Q I s d p 3 var MqttProtoIdentifierv3 = [0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03]; //MQTT proto/version for 311 4 M Q T T 4 var MqttProtoIdentifierv4 = [0x00,0x04,0x4d,0x51,0x54,0x54,0x04]; /** * Construct an MQTT wire protocol message. * @param type MQTT packet type. * @param options optional wire message attributes. * * Optional properties * * messageIdentifier: message ID in the range [0..65535] * payloadMessage: Application Message - PUBLISH only * connectStrings: array of 0 or more Strings to be put into the CONNECT payload * topics: array of strings (SUBSCRIBE, UNSUBSCRIBE) * requestQoS: array of QoS values [0..2] * * "Flag" properties * cleanSession: true if present / false if absent (CONNECT) * willMessage: true if present / false if absent (CONNECT) * isRetained: true if present / false if absent (CONNECT) * userName: true if present / false if absent (CONNECT) * password: true if present / false if absent (CONNECT) * keepAliveInterval: integer [0..65535] (CONNECT) * * @private * @ignore */ var WireMessage = function (type, options) { this.type = type; for (var name in options) { if (options.hasOwnProperty(name)) { this[name] = options[name]; } } }; WireMessage.prototype.encode = function() { // Compute the first byte of the fixed header var first = ((this.type & 0x0f) << 4); /* * Now calculate the length of the variable header + payload by adding up the lengths * of all the component parts */ var remLength = 0; var topicStrLength = new Array(); var destinationNameLength = 0; // if the message contains a messageIdentifier then we need two bytes for that if (this.messageIdentifier != undefined) remLength += 2; switch(this.type) { // If this a Connect then we need to include 12 bytes for its header case MESSAGE_TYPE.CONNECT: switch(this.mqttVersion) { case 3: remLength += MqttProtoIdentifierv3.length + 3; break; case 4: remLength += MqttProtoIdentifierv4.length + 3; break; } remLength += UTF8Length(this.clientId) + 2; if (this.willMessage != undefined) { remLength += UTF8Length(this.willMessage.destinationName) + 2; // Will message is always a string, sent as UTF-8 characters with a preceding length. var willMessagePayloadBytes = this.willMessage.payloadBytes; if (!(willMessagePayloadBytes instanceof Uint8Array)) willMessagePayloadBytes = new Uint8Array(payloadBytes); remLength += willMessagePayloadBytes.byteLength +2; } if (this.userName != undefined) remLength += UTF8Length(this.userName) + 2; if (this.password != undefined) remLength += UTF8Length(this.password) + 2; break; // Subscribe, Unsubscribe can both contain topic strings case MESSAGE_TYPE.SUBSCRIBE: first |= 0x02; // Qos = 1; for ( var i = 0; i < this.topics.length; i++) { topicStrLength[i] = UTF8Length(this.topics[i]); remLength += topicStrLength[i] + 2; } remLength += this.requestedQos.length; // 1 byte for each topic's Qos // QoS on Subscribe only break; case MESSAGE_TYPE.UNSUBSCRIBE: first |= 0x02; // Qos = 1; for ( var i = 0; i < this.topics.length; i++) { topicStrLength[i] = UTF8Length(this.topics[i]); remLength += topicStrLength[i] + 2; } break; case MESSAGE_TYPE.PUBREL: first |= 0x02; // Qos = 1; break; case MESSAGE_TYPE.PUBLISH: if (this.payloadMessage.duplicate) first |= 0x08; first = first |= (this.payloadMessage.qos << 1); if (this.payloadMessage.retained) first |= 0x01; destinationNameLength = UTF8Length(this.payloadMessage.destinationName); remLength += destinationNameLength + 2; var payloadBytes = this.payloadMessage.payloadBytes; remLength += payloadBytes.byteLength; if (payloadBytes instanceof ArrayBuffer) payloadBytes = new Uint8Array(payloadBytes); else if (!(payloadBytes instanceof Uint8Array)) payloadBytes = new Uint8Array(payloadBytes.buffer); break; case MESSAGE_TYPE.DISCONNECT: break; default: ; } // Now we can allocate a buffer for the message var mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format var pos = mbi.length + 1; // Offset of start of variable header var buffer = new ArrayBuffer(remLength + pos); var byteStream = new Uint8Array(buffer); // view it as a sequence of bytes //Write the fixed header into the buffer byteStream[0] = first; byteStream.set(mbi,1); // If this is a PUBLISH then the variable header starts with a topic if (this.type == MESSAGE_TYPE.PUBLISH) pos = writeString(this.payloadMessage.destinationName, destinationNameLength, byteStream, pos); // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time else if (this.type == MESSAGE_TYPE.CONNECT) { switch (this.mqttVersion) { case 3: byteStream.set(MqttProtoIdentifierv3, pos); pos += MqttProtoIdentifierv3.length; break; case 4: byteStream.set(MqttProtoIdentifierv4, pos); pos += MqttProtoIdentifierv4.length; break; } var connectFlags = 0; if (this.cleanSession) connectFlags = 0x02; if (this.willMessage != undefined ) { connectFlags |= 0x04; connectFlags |= (this.willMessage.qos<<3); if (this.willMessage.retained) { connectFlags |= 0x20; } } if (this.userName != undefined) connectFlags |= 0x80; if (this.password != undefined) connectFlags |= 0x40; byteStream[pos++] = connectFlags; pos = writeUint16 (this.keepAliveInterval, byteStream, pos); } // Output the messageIdentifier - if there is one if (this.messageIdentifier != undefined) pos = writeUint16 (this.messageIdentifier, byteStream, pos); switch(this.type) { case MESSAGE_TYPE.CONNECT: pos = writeString(this.clientId, UTF8Length(this.clientId), byteStream, pos); if (this.willMessage != undefined) { pos = writeString(this.willMessage.destinationName, UTF8Length(this.willMessage.destinationName), byteStream, pos); pos = writeUint16(willMessagePayloadBytes.byteLength, byteStream, pos); byteStream.set(willMessagePayloadBytes, pos); pos += willMessagePayloadBytes.byteLength; } if (this.userName != undefined) pos = writeString(this.userName, UTF8Length(this.userName), byteStream, pos); if (this.password != undefined) pos = writeString(this.password, UTF8Length(this.password), byteStream, pos); break; case MESSAGE_TYPE.PUBLISH: // PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters. byteStream.set(payloadBytes, pos); break; // case MESSAGE_TYPE.PUBREC: // case MESSAGE_TYPE.PUBREL: // case MESSAGE_TYPE.PUBCOMP: // break; case MESSAGE_TYPE.SUBSCRIBE: // SUBSCRIBE has a list of topic strings and request QoS for (var i=0; i<this.topics.length; i++) { pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); byteStream[pos++] = this.requestedQos[i]; } break; case MESSAGE_TYPE.UNSUBSCRIBE: // UNSUBSCRIBE has a list of topic strings for (var i=0; i<this.topics.length; i++) pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); break; default: // Do nothing. } return buffer; } function decodeMessage(input,pos) { var startingPos = pos; var first = input[pos]; var type = first >> 4; var messageInfo = first &= 0x0f; pos += 1; // Decode the remaining length (MBI format) var digit; var remLength = 0; var multiplier = 1; do { if (pos == input.length) { return [null,startingPos]; } digit = input[pos++]; remLength += ((digit & 0x7F) * multiplier); multiplier *= 128; } while ((digit & 0x80) != 0); var endPos = pos+remLength; if (endPos > input.length) { return [null,startingPos]; } var wireMessage = new WireMessage(type); switch(type) { case MESSAGE_TYPE.CONNACK: var connectAcknowledgeFlags = input[pos++]; if (connectAcknowledgeFlags & 0x01) wireMessage.sessionPresent = true; wireMessage.returnCode = input[pos++]; break; case MESSAGE_TYPE.PUBLISH: var qos = (messageInfo >> 1) & 0x03; var len = readUint16(input, pos); pos += 2; var topicName = parseUTF8(input, pos, len); pos += len; // If QoS 1 or 2 there will be a messageIdentifier if (qos > 0) { wireMessage.messageIdentifier = readUint16(input, pos); pos += 2; } var message = new Paho.MQTT.Message(input.subarray(pos, endPos)); if ((messageInfo & 0x01) == 0x01) message.retained = true; if ((messageInfo & 0x08) == 0x08) message.duplicate = true; message.qos = qos; message.destinationName = topicName; wireMessage.payloadMessage = message; break; case MESSAGE_TYPE.PUBACK: case MESSAGE_TYPE.PUBREC: case MESSAGE_TYPE.PUBREL: case MESSAGE_TYPE.PUBCOMP: case MESSAGE_TYPE.UNSUBACK: wireMessage.messageIdentifier = readUint16(input, pos); break; case MESSAGE_TYPE.SUBACK: wireMessage.messageIdentifier = readUint16(input, pos); pos += 2; wireMessage.returnCode = input.subarray(pos, endPos); break; default: ; } return [wireMessage,endPos]; } function writeUint16(input, buffer, offset) { buffer[offset++] = input >> 8; //MSB buffer[offset++] = input % 256; //LSB return offset; } function writeString(input, utf8Length, buffer, offset) { offset = writeUint16(utf8Length, buffer, offset); stringToUTF8(input, buffer, offset); return offset + utf8Length; } function readUint16(buffer, offset) { return 256*buffer[offset] + buffer[offset+1]; } /** * Encodes an MQTT Multi-Byte Integer * @private */ function encodeMBI(number) { var output = new Array(1); var numBytes = 0; do { var digit = number % 128; number = number >> 7; if (number > 0) { digit |= 0x80; } output[numBytes++] = digit; } while ( (number > 0) && (numBytes<4) ); return output; } /** * Takes a String and calculates its length in bytes when encoded in UTF8. * @private */ function UTF8Length(input) { var output = 0; for (var i = 0; i<input.length; i++) { var charCode = input.charCodeAt(i); if (charCode > 0x7FF) { // Surrogate pair means its a 4 byte character if (0xD800 <= charCode && charCode <= 0xDBFF) { i++; output++; } output +=3; } else if (charCode > 0x7F) output +=2; else output++; } return output; } /** * Takes a String and writes it into an array as UTF8 encoded bytes. * @private */ function stringToUTF8(input, output, start) { var pos = start; for (var i = 0; i<input.length; i++) { var charCode = input.charCodeAt(i); // Check for a surrogate pair. if (0xD800 <= charCode && charCode <= 0xDBFF) { var lowCharCode = input.charCodeAt(++i); if (isNaN(lowCharCode)) { throw new Error(format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode])); } charCode = ((charCode - 0xD800)<<10) + (lowCharCode - 0xDC00) + 0x10000; } if (charCode <= 0x7F) { output[pos++] = charCode; } else if (charCode <= 0x7FF) { output[pos++] = charCode>>6 & 0x1F | 0xC0; output[pos++] = charCode & 0x3F | 0x80; } else if (charCode <= 0xFFFF) { output[pos++] = charCode>>12 & 0x0F | 0xE0; output[pos++] = charCode>>6 & 0x3F | 0x80; output[pos++] = charCode & 0x3F | 0x80; } else { output[pos++] = charCode>>18 & 0x07 | 0xF0; output[pos++] = charCode>>12 & 0x3F | 0x80; output[pos++] = charCode>>6 & 0x3F | 0x80; output[pos++] = charCode & 0x3F | 0x80; }; } return output; } function parseUTF8(input, offset, length) { var output = ""; var utf16; var pos = offset; while (pos < offset+length) { var byte1 = input[pos++]; if (byte1 < 128) utf16 = byte1; else { var byte2 = input[pos++]-128; if (byte2 < 0) throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16),""])); if (byte1 < 0xE0) // 2 byte character utf16 = 64*(byte1-0xC0) + byte2; else { var byte3 = input[pos++]-128; if (byte3 < 0) throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16)])); if (byte1 < 0xF0) // 3 byte character utf16 = 4096*(byte1-0xE0) + 64*byte2 + byte3; else { var byte4 = input[pos++]-128; if (byte4 < 0) throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); if (byte1 < 0xF8) // 4 byte character utf16 = 262144*(byte1-0xF0) + 4096*byte2 + 64*byte3 + byte4; else // longer encodings are not supported throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); } } } if (utf16 > 0xFFFF) // 4 byte character - express as a surrogate pair { utf16 -= 0x10000; output += String.fromCharCode(0xD800 + (utf16 >> 10)); // lead character utf16 = 0xDC00 + (utf16 & 0x3FF); // trail character } output += String.fromCharCode(utf16); } return output; } /** * Repeat keepalive requests, monitor responses. * @ignore */ var Pinger = function(client, window, keepAliveInterval) { this._client = client; this._window = window; this._keepAliveInterval = keepAliveInterval*1000; this.isReset = false; var pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode(); var doTimeout = function (pinger) { return function () { return doPing.apply(pinger); }; }; /** @ignore */ var doPing = function() { if (!this.isReset) { this._client._trace("Pinger.doPing", "Timed out"); this._client._disconnected( ERROR.PING_TIMEOUT.code , format(ERROR.PING_TIMEOUT)); } else { this.isReset = false; this._client._trace("Pinger.doPing", "send PINGREQ"); this._client.socket.send(pingReq); this.timeout = this._window.setTimeout(doTimeout(this), this._keepAliveInterval); } } this.reset = function() { this.isReset = true; this._window.clearTimeout(this.timeout); if (this._keepAliveInterval > 0) this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval); } this.cancel = function() { this._window.clearTimeout(this.timeout); } }; /** * Reconnect timer * @ignore */ var Reconnector = function(client, window, reconnectInterval) { this._client = client; this._window = window; this._reconnectInterval = reconnectInterval*1000; var doTimeout = function (reconnector) { return function () { return doReconnect.apply(reconnector); }; }; /** @ignore */ var doReconnect = function() { if (this._client.connected) { this._client._trace("Reconnector.doReconnect", "ALREADY CONNECTED"); this._window.clearTimeout(this.reconnectorTimer); } else { this._client._trace("Reconnector.doReconnect", "reconnecting"); if (this._client.connectOptions.uris) { this._client.hostIndex = 0; this._client._doConnect(this._client.connectOptions.uris[0]); } else { this._client._doConnect(this._client.uri); } this.reconnectorTimer = this._window.setTimeout(doTimeout(this), this._reconnectInterval); } } this.reset = function() { this._window.clearTimeout(this.reconnectorTimer); this.reconnectorTimer = this._window.setTimeout(doTimeout(this), this._reconnectInterval); } this.cancel = function() { this._window.clearTimeout(this.reconnectorTimer); } }; /** * Monitor request completion. * @ignore */ var Timeout = function(client, window, timeoutSeconds, action, args) { this._window = window; if (!timeoutSeconds) timeoutSeconds = 30; var doTimeout = function (action, client, args) { return function () { return action.apply(client, args); }; }; this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000); this.cancel = function() { this._window.clearTimeout(this.timeout); } }; /* * Internal implementation of the Websockets MQTT V3.1 client. * * @name Paho.MQTT.ClientImpl @constructor * @param {String} host the DNS nameof the webSocket host. * @param {Number} port the port number for that host. * @param {String} clientId the MQ client identifier. */ var ClientImpl = function (uri, host, port, path, clientId) { // Check dependencies are satisfied in this browser. if (!("WebSocket" in global && global["WebSocket"] !== null)) { throw new Error(format(ERROR.UNSUPPORTED, ["WebSocket"])); } if (!("localStorage" in global && global["localStorage"] !== null)) { localStorage = { store: {}, setItem: function (key, val) { this.store[key] = val; }, getItem: function (key) { return this.store[key]; }, removeItem: function (key) { delete this.store[key]; } }; } if (!("ArrayBuffer" in global && global["ArrayBuffer"] !== null)) { throw new Error(format(ERROR.UNSUPPORTED, ["ArrayBuffer"])); } this._trace("Paho.MQTT.Client", uri, host, port, path, clientId); this.host = host; this.port = port; this.path = path; this.uri = uri; this.clientId = clientId; this._wsuri = null; // Local storagekeys are qualified with the following string. // The conditional inclusion of path in the key is for backward // compatibility to when the path was not configurable and assumed to // be /mqtt this._localKey=host+":"+port+(path!="/mqtt"?":"+path:"")+":"+clientId+":"; // Create private instance-only message queue // Internal queue of messages to be sent, in sending order. this._msg_queue = []; this._buffered_queue = []; // Messages we have sent and are expecting a response for, indexed by their respective message ids. this._sentMessages = {}; // Messages we have received and acknowleged and are expecting a confirm message for // indexed by their respective message ids. this._receivedMessages = {}; // Internal list of callbacks to be executed when messages // have been successfully sent over web socket, e.g. disconnect // when it doesn't have to wait for ACK, just message is dispatched. this._notify_msg_sent = {}; // Unique identifier for SEND messages, incrementing // counter as messages are sent. this._message_identifier = 1; // Used to determine the transmission sequence of stored sent messages. this._sequence = 0; // Load the local state, if any, from the saved version, only restore state relevant to this client. for (var key in localStorage) if ( key.indexOf("Sent:"+this._localKey) == 0 || key.indexOf("Received:"+this._localKey) == 0) this.restore(key); }; // Messaging Client public instance members. ClientImpl.prototype.host; ClientImpl.prototype.port; ClientImpl.prototype.path; ClientImpl.prototype.uri; ClientImpl.prototype.clientId; // Messaging Client private instance members. ClientImpl.prototype.socket; /* true once we have received an acknowledgement to a CONNECT packet. */ ClientImpl.prototype.connected = false; /* The largest message identifier allowed, may not be larger than 2**16 but * if set smaller reduces the maximum number of outbound messages allowed. */ ClientImpl.prototype.maxMessageIdentifier = 65536; ClientImpl.prototype.connectOptions; ClientImpl.prototype.hostIndex; ClientImpl.prototype.onConnected; ClientImpl.prototype.onConnectionLost; ClientImpl.prototype.onMessageDelivered; ClientImpl.prototype.onMessageArrived; ClientImpl.prototype.traceFunction; ClientImpl.prototype._msg_queue = null; ClientImpl.prototype._buffered_queue = null; ClientImpl.prototype._connectTimeout; /* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */ ClientImpl.prototype.sendPinger = null; /* The receivePinger monitors how long we allow before we require evidence that the server is alive. */ ClientImpl.prototype.receivePinger = null; /* The reconnector indicates that reconnection operation is active */ ClientImpl.prototype.reconnector = null; ClientImpl.prototype.disconnectedPublishing = false; ClientImpl.prototype.disconnectedBufferSize = 5000; ClientImpl.prototype.receiveBuffer = null; ClientImpl.prototype._traceBuffer = null; ClientImpl.prototype._MAX_TRACE_ENTRIES = 100; ClientImpl.prototype.connect = function (connectOptions) { var connectOptionsMasked = this._traceMask(connectOptions, "password"); this._trace("Client.connect", connectOptionsMasked, this.socket, this.connected); if (this.connected) throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); if (this.socket) throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); this.connectOptions = connectOptions; if (connectOptions.uris) { this.hostIndex = 0; this._doConnect(connectOptions.uris[0]); } else { this._doConnect(this.uri); } }; ClientImpl.prototype.subscribe = function (filter, subscribeOptions) { this._trace("Client.subscribe", filter, subscribeOptions); if (!this.connected) throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); var wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE); wireMessage.topics=[filter]; if (subscribeOptions.qos != undefined) wireMessage.requestedQos = [subscribeOptions.qos]; else wireMessage.requestedQos = [0]; if (subscribeOptions.onSuccess) { wireMessage.onSuccess = function(grantedQos) {subscribeOptions.onSuccess({invocationContext:subscribeOptions.invocationContext,grantedQos:grantedQos});}; } if (subscribeOptions.onFailure) { wireMessage.onFailure = function(errorCode) {subscribeOptions.onFailure({invocationContext:subscribeOptions.invocationContext,errorCode:errorCode});}; } if (subscribeOptions.timeout) { wireMessage.timeOut = new Timeout(this, window, subscribeOptions.timeout, subscribeOptions.onFailure , [{invocationContext:subscribeOptions.invocationContext, errorCode:ERROR.SUBSCRIBE_TIMEOUT.code, errorMessage:format(ERROR.SUBSCRIBE_TIMEOUT)}]); } // All subscriptions return a SUBACK. this._requires_ack(wireMessage); this._schedule_message(wireMessage); }; /** @ignore */ ClientImpl.prototype.unsubscribe = function(filter, unsubscribeOptions) { this._trace("Client.unsubscribe", filter, unsubscribeOptions); if (!this.connected) throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); var wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE); wireMessage.topics = [filter]; if (unsubscribeOptions.onSuccess) { wireMessage.callback = function() {unsubscribeOptions.onSuccess({invocationContext:unsubscribeOptions.invocationContext});}; } if (unsubscribeOptions.timeout) { wireMessage.timeOut = new Timeout(this, window, unsubscribeOptions.timeout, unsubscribeOptions.onFailure , [{invocationContext:unsubscribeOptions.invocationContext, errorCode:ERROR.UNSUBSCRIBE_TIMEOUT.code, errorMessage:format(ERROR.UNSUBSCRIBE_TIMEOUT)}]); } // All unsubscribes return a SUBACK. this._requires_ack(wireMessage); this._schedule_message(wireMessage); }; ClientImpl.prototype.send = function (message) { this._trace("Client.send", message); if (!this.connected) { if (this.reconnector && this.disconnectedPublishing) { //this._trace("Client.send", this._buffered_queue.length, this.disconnectedBufferSize); if (this._buffered_queue.length === this.disconnectedBufferSize) { throw new Error(format(ERROR.BUFFER_FULL, [this._buffered_queue.length])); } else { this._buffered_queue.push(message); return; } } else { throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); } } wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH); wireMessage.payloadMessage = message; if (message.qos > 0) this._requires_ack(wireMessage); else if (this.onMessageDelivered) this._notify_msg_sent[wireMessage] = this.onMessageDelivered(wireMessage.payloadMessage); this._schedule_message(wireMessage); }; ClientImpl.prototype.disconnect = function () { this._trace("Client.disconnect"); if (!this.socket) throw new Error(format(ERROR.INVALID_STATE, ["not connecting or connected"])); wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT); // Run the disconnected call back as soon as the message has been sent, // in case of a failure later on in the disconnect processing. // as a consequence, the _disconected call back may be run several times. this._notify_msg_sent[wireMessage] = scope(this._disconnected, this); this._schedule_message(wireMessage); }; ClientImpl.prototype.getTraceLog = function () { if ( this._traceBuffer !== null ) { this._trace("Client.getTraceLog", new Date()); this._trace("Client.getTraceLog in flight messages", this._sentMessages.length); for (var key in this._sentMessages) this._trace("_sentMessages ",key, this._sentMessages[key]); for (var key in this._receivedMessages) this._trace("_receivedMessages ",key, this._receivedMessages[key]); return this._traceBuffer; } }; ClientImpl.prototype.startTrace = function () { if ( this._traceBuffer === null ) { this._traceBuffer = []; } this._trace("Client.startTrace", new Date(), version); }; ClientImpl.prototype.stopTrace = function () { delete this._traceBuffer; }; ClientImpl.prototype._doConnect = function (wsurl) { // When the socket is open, this client will send the CONNECT WireMessage using the saved parameters. if (this.connectOptions.useSSL) { var uriParts = wsurl.split(":"); uriParts[0] = "wss"; wsurl = uriParts.join(":"); } this._wsuri = wsurl; this.connected = false; if (this.connectOptions.mqttVersion < 4) { this.socket = new WebSocket(wsurl, ["mqttv3.1"]); } else { this.socket = new WebSocket(wsurl, ["mqtt"]); } this.socket.binaryType = 'arraybuffer'; this.socket.onopen = scope(this._on_socket_open, this); this.socket.onmessage = scope(this._on_socket_message, this); this.socket.onerror = scope(this._on_socket_error, this); this.socket.onclose = scope(this._on_socket_close, this); this.sendPinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); this.receivePinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); this._connectTimeout = new Timeout(this, window, this.connectOptions.timeout, this._disconnected, [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)]); }; // Schedule a new message to be sent over the WebSockets // connection. CONNECT messages cause WebSocket connection // to be started. All other messages are queued internally // until this has happened. When WS connection starts, process // all outstanding messages. ClientImpl.prototype._schedule_message = function (message) { this._msg_queue.push(message); // Process outstanding messages in the queue if we have an open socket, and have received CONNACK. if (this.connected && this.reconnector === null) { this._process_queue(); } }; ClientImpl.prototype.store = function(prefix, wireMessage) { var storedMessage = {type:wireMessage.type, messageIdentifier:wireMessage.messageIdentifier, version:1}; switch(wireMessage.type) { case MESSAGE_TYPE.PUBLISH: if(wireMessage.pubRecReceived) storedMessage.pubRecReceived = true; // Convert the payload to a hex string. storedMessage.payloadMessage = {}; var hex = ""; var messageBytes = wireMessage.payloadMessage.payloadBytes; for (var i=0; i<messageBytes.length; i++) { if (messageBytes[i] <= 0xF) hex = hex+"0"+messageBytes[i].toString(16); else hex = hex+messageBytes[i].toString(16); } storedMessage.payloadMessage.payloadHex = hex; storedMessage.payloadMessage.qos = wireMessage.payloadMessage.qos; storedMessage.payloadMessage.destinationName = wireMessage.payloadMessage.destinationName; if (wireMessage.payloadMessage.duplicate) storedMessage.payloadMessage.duplicate = true; if (wireMessage.payloadMessage.retained) storedMessage.payloadMessage.retained = true; // Add a sequence number to sent messages. if ( prefix.indexOf("Sent:") == 0 ) { if ( wireMessage.sequence === undefined ) wireMessage.sequence = ++this._sequence; storedMessage.sequence = wireMessage.sequence; } break; default: throw Error(format(ERROR.INVALID_STORED_DATA, [key, storedMessage])); } localStorage.setItem(prefix+this._localKey+wireMessage.messageIdentifier, JSON.stringify(storedMessage)); }; ClientImpl.prototype.restore = function(key) { var value = localStorage.getItem(key); var storedMessage = JSON.parse(value); var wireMessage = new WireMessage(storedMessage.type, storedMessage); switch(storedMessage.type) { case MESSAGE_TYPE.PUBLISH: // Replace the payload message with a Message object. var hex = storedMessage.payloadMessage.payloadHex; var buffer = new ArrayBuffer((hex.length)/2); var byteStream = new Uint8Array(buffer); var i = 0; while (hex.length >= 2) { var x = parseInt(hex.substring(0, 2), 16); hex = hex.substring(2, hex.length); byteStream[i++] = x; } var payloadMessage = new Paho.MQTT.Message(byteStream); payloadMessage.qos = storedMessage.payloadMessage.qos; payloadMessage.destinationName = storedMessage.payloadMessage.destinationName; if (storedMessage.payloadMessage.duplicate) payloadMessage.duplicate = true; if (storedMessage.payloadMessage.retained) payloadMessage.retained = true; wireMessage.payloadMessage = payloadMessage; break; default: throw Error(format(ERROR.INVALID_STORED_DATA, [key, value])); } if (key.indexOf("Sent:"+this._localKey) == 0) { wireMessage.payloadMessage.duplicate = true; this._sentMessages[wireMessage.messageIdentifier] = wireMessage; } else if (key.indexOf("Received:"+this._localKey) == 0) { this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; } }; ClientImpl.prototype._process_queue = function () { var message = null; // Process messages in order they were added var fifo = this._msg_queue.reverse(); // Send all queued messages down socket connection while ((message = fifo.pop())) { this._socket_send(message); // Notify listeners that message was successfully sent if (this._notify_msg_sent[message]) { this._notify_msg_sent[message](); delete this._notify_msg_sent[message]; } } }; /** * Expect an ACK response for this message. Add message to the set of in progress * messages and set an unused identifier in this message. * @ignore */ ClientImpl.prototype._requires_ack = function (wireMessage) { var messageCount = Object.keys(this._sentMessages).length; if (messageCount > this.maxMessageIdentifier) throw Error ("Too many messages:"+messageCount); while(this._sentMessages[this._message_identifier] !== undefined) { this._message_identifier++; } wireMessage.messageIdentifier = this._message_identifier; this._sentMessages[wireMessage.messageIdentifier] = wireMessage; if (wireMessage.type === MESSAGE_TYPE.PUBLISH) { this.store("Sent:", wireMessage); } if (this._message_identifier === this.maxMessageIdentifier) { this._message_identifier = 1; } }; /** * Called when the underlying websocket has been opened. * @ignore */ ClientImpl.prototype._on_socket_open = function () { // Create the CONNECT message object. var wireMessage = new WireMessage(MESSAGE_TYPE.CONNECT, this.connectOptions); wireMessage.clientId = this.clientId; this._socket_send(wireMessage); }; /** * Called when the underlying websocket has received a complete packet. * @ignore */ ClientImpl.prototype._on_socket_message = function (event) { this._trace("Client._on_socket_message", event.data); var messages = this._deframeMessages(event.data); for (var i = 0; i < messages.length; i+=1) { this._handleMessage(messages[i]); } } ClientImpl.prototype._deframeMessages = function(data) { var byteArray = new Uint8Array(data); if (this.receiveBuffer) { var newData = new Uint8Array(this.receiveBuffer.length+byteArray.length); newData.set(this.receiveBuffer); newData.set(byteArray,this.receiveBuffer.length); byteArray = newData; delete this.receiveBuffer; } try { var offset = 0; var messages = []; while(offset < byteArray.length) { var result = decodeMessage(byteArray,offset); var wireMessage = result[0]; offset = result[1]; if (wireMessage !== null) { messages.push(wireMessage); } else { break; } } if (offset < byteArray.length) { this.receiveBuffer = byteArray.subarray(offset); } } catch (error) { this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,error.stack.toString()])); return; } return messages; } ClientImpl.prototype._handleMessage = function(wireMessage) { this._trace("Client._handleMessage", wireMessage); try { switch(wireMessage.type) { case MESSAGE_TYPE.CONNACK: this._connectTimeout.cancel(); this._connectTimeout = null; // If we have started using clean session then clear up the local state. if (this.connectOptions.cleanSession) { for (var key in this._sentMessages) { var sentMessage = this._sentMessages[key]; localStorage.removeItem("Sent:"+this._localKey+sentMessage.messageIdentifier); } this._sentMessages = {}; for (var key in this._receivedMessages) { var receivedMessage = this._receivedMessages[key]; localStorage.removeItem("Received:"+this._localKey+receivedMessage.messageIdentifier); } this._receivedMessages = {}; } // Client connected and ready for business. if (wireMessage.returnCode === 0) { this.connected = true; // Jump to the end of the list of uris and stop looking for a good host. if (this.connectOptions.uris) this.hostIndex = this.connectOptions.uris.length; } else { this._disconnected(ERROR.CONNACK_RETURNCODE.code , format(ERROR.CONNACK_RETURNCODE, [wireMessage.returnCode, CONNACK_RC[wireMessage.returnCode]])); break; } // Resend messages. var sequencedMessages = new Array(); for (var msgId in this._sentMessages) { if (this._sentMessages.hasOwnProperty(msgId)) sequencedMessages.push(this._sentMessages[msgId]); } // Sort sentMessages into the original sent order. var sequencedMessages = sequencedMessages.sort(function(a,b) {return a.sequence - b.sequence;} ); for (var i=0, len=sequencedMessages.length; i<len; i++) { var sentMessage = sequencedMessages[i]; if (sentMessage.type == MESSAGE_TYPE.PUBLISH && sentMessage.pubRecReceived) { var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:sentMessage.messageIdentifier}); this._schedule_message(pubRelMessage); } else { this._schedule_message(sentMessage); } } // Send buffered messages if (this.reconnector) { var fifo = this._buffered_queue.reverse(); var message = null; while(message = fifo.pop()) { var wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH); wireMessage.payloadMessage = message; if (message.qos > 0) this._requires_ack(wireMessage); else if (this.onMessageDelivered) this._notify_msg_sent[wireMessage] = this.onMessageDelivered(wireMessage.payloadMessage); this._schedule_message(wireMessage); } this._buffered_queue = []; } // Execute the connectOptions.onSuccess callback if there is one. if (this.connectOptions.onSuccess && (this.reconnector == null)) { this.connectOptions.onSuccess({invocationContext:this.connectOptions.invocationContext}); } reconnect = false; if (this.connectOptions.reconnect && this.reconnector) { reconnect = true; this.reconnector.cancel(); this.reconnector = null; // Execute the onConnected callback if there is one. if (this.onConnected) { this.onConnected({reconnect:reconnect, uri:this._wsuri}); } } // Process all queued messages now that the connection is established. this._process_queue(); break; case MESSAGE_TYPE.PUBLISH: this._receivePublish(wireMessage); break; case MESSAGE_TYPE.PUBACK: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; // If this is a re flow of a PUBACK after we have restarted receivedMessage will not exist. if (sentMessage) { delete this._sentMessages[wireMessage.messageIdentifier]; localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier); if (this.onMessageDelivered) this.onMessageDelivered(sentMessage.payloadMessage); } break; case MESSAGE_TYPE.PUBREC: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; // If this is a re flow of a PUBREC after we have restarted receivedMessage will not exist. if (sentMessage) { sentMessage.pubRecReceived = true; var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:wireMessage.messageIdentifier}); this.store("Sent:", sentMessage); this._schedule_message(pubRelMessage); } break; case MESSAGE_TYPE.PUBREL: var receivedMessage = this._receivedMessages[wireMessage.messageIdentifier]; localStorage.removeItem("Received:"+this._localKey+wireMessage.messageIdentifier); // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist. if (receivedMessage) { this._receiveMessage(receivedMessage); delete this._receivedMessages[wireMessage.messageIdentifier]; } // Always flow PubComp, we may have previously flowed PubComp but the server lost it and restarted. var pubCompMessage = new WireMessage(MESSAGE_TYPE.PUBCOMP, {messageIdentifier:wireMessage.messageIdentifier}); this._schedule_message(pubCompMessage); break; case MESSAGE_TYPE.PUBCOMP: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; delete this._sentMessages[wireMessage.messageIdentifier]; localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier); if (this.onMessageDelivered) this.onMessageDelivered(sentMessage.payloadMessage); break; case MESSAGE_TYPE.SUBACK: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; if (sentMessage) { if(sentMessage.timeOut) sentMessage.timeOut.cancel(); // This will need to be fixed when we add multiple topic support if (wireMessage.returnCode[0] === 0x80) { if (sentMessage.onFailure) { sentMessage.onFailure(wireMessage.returnCode); } } else if (sentMessage.onSuccess) { sentMessage.onSuccess(wireMessage.returnCode); } delete this._sentMessages[wireMessage.messageIdentifier]; } break; case MESSAGE_TYPE.UNSUBACK: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; if (sentMessage) { if (sentMessage.timeOut) sentMessage.timeOut.cancel(); if (sentMessage.callback) { sentMessage.callback(); } delete this._sentMessages[wireMessage.messageIdentifier]; } break; case MESSAGE_TYPE.PINGRESP: /* The sendPinger or receivePinger may have sent a ping, the receivePinger has already been reset. */ this.sendPinger.reset(); break; case MESSAGE_TYPE.DISCONNECT: // Clients do not expect to receive disconnect packets. this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); break; default: this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); }; } catch (error) { this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,error.stack.toString()])); return; } }; /** @ignore */ ClientImpl.prototype._on_socket_error = function (error) { this._disconnected(ERROR.SOCKET_ERROR.code , format(ERROR.SOCKET_ERROR, [error.data])); }; /** @ignore */ ClientImpl.prototype._on_socket_close = function () { this._disconnected(ERROR.SOCKET_CLOSE.code , format(ERROR.SOCKET_CLOSE)); }; /** @ignore */ ClientImpl.prototype._socket_send = function (wireMessage) { if (wireMessage.type == 1) { var wireMessageMasked = this._traceMask(wireMessage, "password"); this._trace("Client._socket_send", wireMessageMasked); } else this._trace("Client._socket_send", wireMessage); this.socket.send(wireMessage.encode()); /* We have proved to the server we are alive. */ this.sendPinger.reset(); }; /** @ignore */ ClientImpl.prototype._receivePublish = function (wireMessage) { switch(wireMessage.payloadMessage.qos) { case "undefined": case 0: this._receiveMessage(wireMessage); break; case 1: var pubAckMessage = new WireMessage(MESSAGE_TYPE.PUBACK, {messageIdentifier:wireMessage.messageIdentifier}); this._schedule_message(pubAckMessage); this._receiveMessage(wireMessage); break; case 2: this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; this.store("Received:", wireMessage); var pubRecMessage = new WireMessage(MESSAGE_TYPE.PUBREC, {messageIdentifier:wireMessage.messageIdentifier}); this._schedule_message(pubRecMessage); break; default: throw Error("Invaild qos="+wireMmessage.payloadMessage.qos); }; }; /** @ignore */ ClientImpl.prototype._receiveMessage = function (wireMessage) { if (this.onMessageArrived) { this.onMessageArrived(wireMessage.payloadMessage); } }; /** * Client has connected. * @param {reconnect} [boolean] indicate if this was a result of reconnect operation. * @param {uri} [string] fully qualified WebSocket URI of the server. */ ClientImpl.prototype._connected = function (reconnect, uri) { // Execute the onConnected callback if there is one. if (this.onConnected) this.onConnected({reconnect:reconnect, uri:uri}); }; /** * Client has disconnected either at its own request or because the server * or network disconnected it. Remove all non-durable state. * @param {errorCode} [number] the error number. * @param {errorText} [string] the error text. * @ignore */ ClientImpl.prototype._disconnected = function (errorCode, errorText) { this._trace("Client._disconnected", errorCode, errorText, new Date()); if (this.connected && errorCode === ERROR.CONNECT_TIMEOUT.code) { return; } this.sendPinger.cancel(); this.receivePinger.cancel(); if (this._connectTimeout) { this._connectTimeout.cancel(); this._connectTimeout = null; } if (!this.reconnector) { // Clear message buffers. this._msg_queue = []; this._notify_msg_sent = {}; } if (this.socket) { // Cancel all socket callbacks so that they cannot be driven again by this socket. this.socket.onopen = null; this.socket.onmessage = null; this.socket.onerror = null; this.socket.onclose = null; if (this.socket.readyState === 1) this.socket.close(); delete this.socket; } if (this.connectOptions.uris && this.hostIndex < this.connectOptions.uris.length-1) { // Try the next host. this.hostIndex++; this._doConnect(this.connectOptions.uris[this.hostIndex]); } else { if (errorCode === undefined) { errorCode = ERROR.OK.code; errorText = format(ERROR.OK); } // Run any application callbacks last as they may attempt to reconnect and hence create a new socket. if (this.connected) { this.connected = false; // Execute the connectionLostCallback if there is one, and we were connected. if (this.onConnectionLost) { reconnect = false; if (this.connectOptions.reconnect) reconnect = this.connectOptions.reconnect; this.onConnectionLost({errorCode:errorCode, errorMessage:errorText, reconnect:reconnect, uri:this._wsuri}); } if (errorCode !== ERROR.OK.code && this.connectOptions.reconnect) { this._trace("Client._disconnected", "starting auto reconnect"); this.reconnector = new Reconnector(this, window, this.connectOptions.reconnectInterval); this.reconnector.reset(); } } else if (this.reconnector) { this._trace("Client._disconnected", "auto reconnect is already in progress", new Date()); } else { // Otherwise we never had a connection, so indicate that the connect has failed. if (this.connectOptions.mqttVersion === 4 && this.connectOptions.mqttVersionExplicit === false) { this._trace("Failed to connect V4, dropping back to V3") this.connectOptions.mqttVersion = 3; if (this.connectOptions.uris) { this.hostIndex = 0; this._doConnect(this.connectOptions.uris[0]); } else { this._doConnect(this.uri); } } else if(this.connectOptions.onFailure) { this.connectOptions.onFailure({invocationContext:this.connectOptions.invocationContext, errorCode:errorCode, errorMessage:errorText}); } } } }; /** @ignore */ ClientImpl.prototype._trace = function () { // Pass trace message back to client's callback function if (this.traceFunction) { for (var i in arguments) { if (typeof arguments[i] !== "undefined") arguments[i] = JSON.stringify(arguments[i]); } var record = Array.prototype.slice.call(arguments).join(""); this.traceFunction ({severity: "Debug", message: record }); } //buffer style trace if ( this._traceBuffer !== null ) { for (var i = 0, max = arguments.length; i < max; i++) { if ( this._traceBuffer.length == this._MAX_TRACE_ENTRIES ) { this._traceBuffer.shift(); } if (i === 0) this._traceBuffer.push(arguments[i]); else if (typeof arguments[i] === "undefined" ) this._traceBuffer.push(arguments[i]); else this._traceBuffer.push(" "+JSON.stringify(arguments[i])); }; }; }; /** @ignore */ ClientImpl.prototype._traceMask = function (traceObject, masked) { var traceObjectMasked = {}; for (var attr in traceObject) { if (traceObject.hasOwnProperty(attr)) { if (attr == masked) traceObjectMasked[attr] = "******"; else traceObjectMasked[attr] = traceObject[attr]; } } return traceObjectMasked; }; // ------------------------------------------------------------------------ // Public Programming interface. // ------------------------------------------------------------------------ /** * The JavaScript application communicates to the server using a {@link Paho.MQTT.Client} object. * <p> * Most applications will create just one Client object and then call its connect() method, * however applications can create more than one Client object if they wish. * In this case the combination of host, port and clientId attributes must be different for each Client object. * <p> * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods * (even though the underlying protocol exchange might be synchronous in nature). * This means they signal their completion by calling back to the application, * via Success or Failure callback functions provided by the application on the method in question. * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime * of the script that made the invocation. * <p> * In contrast there are some callback functions, most notably <i>onMessageArrived</i>, * that are defined on the {@link Paho.MQTT.Client} object. * These may get called multiple times, and aren't directly related to specific method invocations made by the client. * * @name Paho.MQTT.Client * * @constructor * * @param {string} host - the address of the messaging server, as a fully qualified WebSocket URI, as a DNS name or dotted decimal IP address. * @param {number} port - the port number to connect to - only required if host is not a URI * @param {string} path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'. * @param {string} clientId - the Messaging client identifier, between 1 and 23 characters in length. * * @property {string} host - <i>read only</i> the server's DNS hostname or dotted decimal IP address. * @property {number} port - <i>read only</i> the server's port. * @property {string} path - <i>read only</i> the server's path. * @property {string} clientId - <i>read only</i> used when connecting to the server. * @property {function} onConnectionLost - called when a connection has been lost. * after a connect() method has succeeded. * Establish the call back used when a connection has been lost. The connection may be * lost because the client initiates a disconnect or because the server or network * cause the client to be disconnected. The disconnect call back may be called without * the connectionComplete call back being invoked if, for example the client fails to * connect. * A single response object parameter is passed to the onConnectionLost callback containing the following fields: * <ol> * <li>errorCode * <li>errorMessage * </ol> * @property {function} onMessageDelivered called when a message has been delivered. * All processing that this Client will ever do has been completed. So, for example, * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server * and the message has been removed from persistent storage before this callback is invoked. * Parameters passed to the onMessageDelivered callback are: * <ol> * <li>{@link Paho.MQTT.Message} that was delivered. * </ol> * @property {function} onMessageArrived called when a message has arrived in this Paho.MQTT.client. * Parameters passed to the onMessageArrived callback are: * <ol> * <li>{@link Paho.MQTT.Message} that has arrived. * </ol> */ var Client = function (host, port, path, clientId) { var uri; if (typeof host !== "string") throw new Error(format(ERROR.INVALID_TYPE, [typeof host, "host"])); if (arguments.length == 2) { // host: must be full ws:// uri // port: clientId clientId = port; uri = host; var match = uri.match(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/); if (match) { host = match[4]||match[2]; port = parseInt(match[7]); path = match[8]; } else { throw new Error(format(ERROR.INVALID_ARGUMENT,[host,"host"])); } } else { if (arguments.length == 3) { clientId = path; path = "/mqtt"; } if (typeof port !== "number" || port < 0) throw new Error(format(ERROR.INVALID_TYPE, [typeof port, "port"])); if (typeof path !== "string") throw new Error(format(ERROR.INVALID_TYPE, [typeof path, "path"])); var ipv6AddSBracket = (host.indexOf(":") != -1 && host.slice(0,1) != "[" && host.slice(-1) != "]"); uri = "ws://"+(ipv6AddSBracket?"["+host+"]":host)+":"+port+path; } var clientIdLength = 0; for (var i = 0; i<clientId.length; i++) { var charCode = clientId.charCodeAt(i); if (0xD800 <= charCode && charCode <= 0xDBFF) { i++; // Surrogate pair. } clientIdLength++; } if (typeof clientId !== "string" || clientIdLength > 65535) throw new Error(format(ERROR.INVALID_ARGUMENT, [clientId, "clientId"])); var client = new ClientImpl(uri, host, port, path, clientId); this._getHost = function() { return host; }; this._setHost = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getPort = function() { return port; }; this._setPort = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getPath = function() { return path; }; this._setPath = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getURI = function() { return uri; }; this._setURI = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getClientId = function() { return client.clientId; }; this._setClientId = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getOnConnected = function() { return client.onConnected; }; this._setOnConnected = function(newOnConnected) { if (typeof newOnConnected === "function") client.onConnected = newOnConnected; else throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnected, "onConnected"])); }; this._getDisconnectedPublishing = function() { return client.disconnectedPublishing; }; this._setDisconnectedPublishing = function(newDisconnectedPublishing) { client.disconnectedPublishing = newDisconnectedPublishing; } this._getDisconnectedBufferSize = function() { return client.disconnectedBufferSize; }; this._setDisconnectedBufferSize = function(newDisconnectedBufferSize) { client.disconnectedBufferSize = newDisconnectedBufferSize; } this._getOnConnectionLost = function() { return client.onConnectionLost; }; this._setOnConnectionLost = function(newOnConnectionLost) { if (typeof newOnConnectionLost === "function") client.onConnectionLost = newOnConnectionLost; else throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnectionLost, "onConnectionLost"])); }; this._getOnMessageDelivered = function() { return client.onMessageDelivered; }; this._setOnMessageDelivered = function(newOnMessageDelivered) { if (typeof newOnMessageDelivered === "function") client.onMessageDelivered = newOnMessageDelivered; else throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageDelivered, "onMessageDelivered"])); }; this._getOnMessageArrived = function() { return client.onMessageArrived; }; this._setOnMessageArrived = function(newOnMessageArrived) { if (typeof newOnMessageArrived === "function") client.onMessageArrived = newOnMessageArrived; else throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageArrived, "onMessageArrived"])); }; this._getTrace = function() { return client.traceFunction; }; this._setTrace = function(trace) { if(typeof trace === "function"){ client.traceFunction = trace; }else{ throw new Error(format(ERROR.INVALID_TYPE, [typeof trace, "onTrace"])); } }; /** * Connect this Messaging client to its server. * * @name Paho.MQTT.Client#connect * @function * @param {Object} connectOptions - attributes used with the connection. * @param {number} connectOptions.timeout - If the connect has not succeeded within this * number of seconds, it is deemed to have failed. * The default is 30 seconds. * @param {string} connectOptions.userName - Authentication username for this connection. * @param {string} connectOptions.password - Authentication password for this connection. * @param {Paho.MQTT.Message} connectOptions.willMessage - sent by the server when the client * disconnects abnormally. * @param {Number} connectOptions.keepAliveInterval - the server disconnects this client if * there is no activity for this number of seconds. * The default value of 60 seconds is assumed if not set. * @param {boolean} connectOptions.cleanSession - if true(default) the client and server * persistent state is deleted on successful connect. * @param {boolean} connectOptions.useSSL - if present and true, use an SSL Websocket connection. * @param {object} connectOptions.invocationContext - passed to the onSuccess callback or onFailure callback. * @param {function} connectOptions.onSuccess - called when the connect acknowledgement * has been received from the server. * A single response object parameter is passed to the onSuccess callback containing the following fields: * <ol> * <li>invocationContext as passed in to the onSuccess method in the connectOptions. * </ol> * @config {function} [onFailure] called when the connect request has failed or timed out. * A single response object parameter is passed to the onFailure callback containing the following fields: * <ol> * <li>invocationContext as passed in to the onFailure method in the connectOptions. * <li>errorCode a number indicating the nature of the error. * <li>errorMessage text describing the error. * </ol> * @config {Array} [hosts] If present this contains either a set of hostnames or fully qualified * WebSocket URIs (ws://example.com:1883/mqtt), that are tried in order in place * of the host and port paramater on the construtor. The hosts are tried one at at time in order until * one of then succeeds. * @config {Array} [ports] If present the set of ports matching the hosts. If hosts contains URIs, this property * is not used. * @throws {InvalidState} if the client is not in disconnected state. The client must have received connectionLost * or disconnected before calling connect for a second or subsequent time. */ this.connect = function (connectOptions) { connectOptions = connectOptions || {} ; validate(connectOptions, {timeout:"number", userName:"string", password:"string", willMessage:"object", keepAliveInterval:"number", cleanSession:"boolean", useSSL:"boolean", invocationContext:"object", onSuccess:"function", onFailure:"function", hosts:"object", ports:"object", reconnect:"boolean", reconnectInterval:"number", mqttVersion:"number", mqttVersionExplicit:"boolean", uris: "object"}); // If no keep alive interval is set, assume 60 seconds. if (connectOptions.keepAliveInterval === undefined) connectOptions.keepAliveInterval = 60; if (connectOptions.mqttVersion > 4 || connectOptions.mqttVersion < 3) { throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.mqttVersion, "connectOptions.mqttVersion"])); } if (connectOptions.mqttVersion === undefined) { connectOptions.mqttVersionExplicit = false; connectOptions.mqttVersion = 4; } else { connectOptions.mqttVersionExplicit = true; } //Check that if password is set, so is username if (connectOptions.password !== undefined && connectOptions.userName === undefined) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.password, "connectOptions.password"])) if (connectOptions.reconnectInterval === undefined) connectOptions.reconnectInterval = 10; if (connectOptions.willMessage) { if (!(connectOptions.willMessage instanceof Message)) throw new Error(format(ERROR.INVALID_TYPE, [connectOptions.willMessage, "connectOptions.willMessage"])); // The will message must have a payload that can be represented as a string. // Cause the willMessage to throw an exception if this is not the case. connectOptions.willMessage.stringPayload; if (typeof connectOptions.willMessage.destinationName === "undefined") throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.willMessage.destinationName, "connectOptions.willMessage.destinationName"])); } if (typeof connectOptions.cleanSession === "undefined") connectOptions.cleanSession = true; if (connectOptions.hosts) { if (!(connectOptions.hosts instanceof Array) ) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); if (connectOptions.hosts.length <1 ) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); var usingURIs = false; for (var i = 0; i<connectOptions.hosts.length; i++) { if (typeof connectOptions.hosts[i] !== "string") throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); if (/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(connectOptions.hosts[i])) { if (i == 0) { usingURIs = true; } else if (!usingURIs) { throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); } } else if (usingURIs) { throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); } } if (!usingURIs) { if (!connectOptions.ports) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); if (!(connectOptions.ports instanceof Array) ) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); if (connectOptions.hosts.length != connectOptions.ports.length) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); connectOptions.uris = []; for (var i = 0; i<connectOptions.hosts.length; i++) { if (typeof connectOptions.ports[i] !== "number" || connectOptions.ports[i] < 0) throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.ports[i], "connectOptions.ports["+i+"]"])); var host = connectOptions.hosts[i]; var port = connectOptions.ports[i]; var ipv6 = (host.indexOf(":") != -1); uri = "ws://"+(ipv6?"["+host+"]":host)+":"+port+path; connectOptions.uris.push(uri); } } else { connectOptions.uris = connectOptions.hosts; } } client.connect(connectOptions); }; /** * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the filter. * * @name Paho.MQTT.Client#subscribe * @function * @param {string} filter describing the destinations to receive messages from. * <br> * @param {object} subscribeOptions - used to control the subscription * * @param {number} subscribeOptions.qos - the maiximum qos of any publications sent * as a result of making this subscription. * @param {object} subscribeOptions.invocationContext - passed to the onSuccess callback * or onFailure callback. * @param {function} subscribeOptions.onSuccess - called when the subscribe acknowledgement * has been received from the server. * A single response object parameter is passed to the onSuccess callback containing the following fields: * <ol> * <li>invocationContext if set in the subscribeOptions. * </ol> * @param {function} subscribeOptions.onFailure - called when the subscribe request has failed or timed out. * A single response object parameter is passed to the onFailure callback containing the following fields: * <ol> * <li>invocationContext - if set in the subscribeOptions. * <li>errorCode - a number indicating the nature of the error. * <li>errorMessage - text describing the error. * </ol> * @param {number} subscribeOptions.timeout - which, if present, determines the number of * seconds after which the onFailure calback is called. * The presence of a timeout does not prevent the onSuccess * callback from being called when the subscribe completes. * @throws {InvalidState} if the client is not in connected state. */ this.subscribe = function (filter, subscribeOptions) { if (typeof filter !== "string") throw new Error("Invalid argument:"+filter); subscribeOptions = subscribeOptions || {} ; validate(subscribeOptions, {qos:"number", invocationContext:"object", onSuccess:"function", onFailure:"function", timeout:"number" }); if (subscribeOptions.timeout && !subscribeOptions.onFailure) throw new Error("subscribeOptions.timeout specified with no onFailure callback."); if (typeof subscribeOptions.qos !== "undefined" && !(subscribeOptions.qos === 0 || subscribeOptions.qos === 1 || subscribeOptions.qos === 2 )) throw new Error(format(ERROR.INVALID_ARGUMENT, [subscribeOptions.qos, "subscribeOptions.qos"])); client.subscribe(filter, subscribeOptions); }; /** * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter. * * @name Paho.MQTT.Client#unsubscribe * @function * @param {string} filter - describing the destinations to receive messages from. * @param {object} unsubscribeOptions - used to control the subscription * @param {object} unsubscribeOptions.invocationContext - passed to the onSuccess callback or onFailure callback. * @param {function} unsubscribeOptions.onSuccess - called when the unsubscribe acknowledgement has been received from the server. * A single response object parameter is passed to the * onSuccess callback containing the following fields: * <ol> * <li>invocationContext - if set in the unsubscribeOptions. * </ol> * @param {function} unsubscribeOptions.onFailure called when the unsubscribe request has failed or timed out. * A single response object parameter is passed to the onFailure callback containing the following fields: * <ol> * <li>invocationContext - if set in the unsubscribeOptions. * <li>errorCode - a number indicating the nature of the error. * <li>errorMessage - text describing the error. * </ol> * @param {number} unsubscribeOptions.timeout - which, if present, determines the number of seconds * after which the onFailure callback is called. The presence of * a timeout does not prevent the onSuccess callback from being * called when the unsubscribe completes * @throws {InvalidState} if the client is not in connected state. */ this.unsubscribe = function (filter, unsubscribeOptions) { if (typeof filter !== "string") throw new Error("Invalid argument:"+filter); unsubscribeOptions = unsubscribeOptions || {} ; validate(unsubscribeOptions, {invocationContext:"object", onSuccess:"function", onFailure:"function", timeout:"number" }); if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure) throw new Error("unsubscribeOptions.timeout specified with no onFailure callback."); client.unsubscribe(filter, unsubscribeOptions); }; /** * Send a message to the consumers of the destination in the Message. * * @name Paho.MQTT.Client#send * @function * @param {string|Paho.MQTT.Message} topic - <b>mandatory</b> The name of the destination to which the message is to be sent. * - If it is the only parameter, used as Paho.MQTT.Message object. * @param {String|ArrayBuffer} payload - The message data to be sent. * @param {number} qos The Quality of Service used to deliver the message. * <dl> * <dt>0 Best effort (default). * <dt>1 At least once. * <dt>2 Exactly once. * </dl> * @param {Boolean} retained If true, the message is to be retained by the server and delivered * to both current and future subscriptions. * If false the server only delivers the message to current subscribers, this is the default for new Messages. * A received message has the retained boolean set to true if the message was published * with the retained boolean set to true * and the subscrption was made after the message has been published. * @throws {InvalidState} if the client is not connected. */ this.send = function (topic,payload,qos,retained) { var message ; if(arguments.length == 0){ throw new Error("Invalid argument."+"length"); }else if(arguments.length == 1) { if (!(topic instanceof Message) && (typeof topic !== "string")) throw new Error("Invalid argument:"+ typeof topic); message = topic; if (typeof message.destinationName === "undefined") throw new Error(format(ERROR.INVALID_ARGUMENT,[message.destinationName,"Message.destinationName"])); client.send(message); }else { //parameter checking in Message object message = new Message(payload); message.destinationName = topic; if(arguments.length >= 3) message.qos = qos; if(arguments.length >= 4) message.retained = retained; client.send(message); } }; /** * Normal disconnect of this Messaging client from its server. * * @name Paho.MQTT.Client#disconnect * @function * @throws {InvalidState} if the client is already disconnected. */ this.disconnect = function () { client.disconnect(); }; /** * Get the contents of the trace log. * * @name Paho.MQTT.Client#getTraceLog * @function * @return {Object[]} tracebuffer containing the time ordered trace records. */ this.getTraceLog = function () { return client.getTraceLog(); } /** * Start tracing. * * @name Paho.MQTT.Client#startTrace * @function */ this.startTrace = function () { client.startTrace(); }; /** * Stop tracing. * * @name Paho.MQTT.Client#stopTrace * @function */ this.stopTrace = function () { client.stopTrace(); }; this.isConnected = function() { return client.connected; }; }; Client.prototype = { get host() { return this._getHost(); }, set host(newHost) { this._setHost(newHost); }, get port() { return this._getPort(); }, set port(newPort) { this._setPort(newPort); }, get path() { return this._getPath(); }, set path(newPath) { this._setPath(newPath); }, get clientId() { return this._getClientId(); }, set clientId(newClientId) { this._setClientId(newClientId); }, get onConnected() { return this._getOnConnected(); }, set onConnected(newOnConnected) { this._setOnConnected(newOnConnected); }, get disconnectedPublishing() { return this._getDisconnectedPublishing(); }, set disconnectedPublishing(newDisconnectedPublishing) { this._setDisconnectedPublishing(newDisconnectedPublishing); }, get disconnectedBufferSize() { return this._getDisconnectedBufferSize(); }, set disconnectedBufferSize(newDisconnectedBufferSize) { this._setDisconnectedBufferSize(newDisconnectedBufferSize); }, get onConnectionLost() { return this._getOnConnectionLost(); }, set onConnectionLost(newOnConnectionLost) { this._setOnConnectionLost(newOnConnectionLost); }, get onMessageDelivered() { return this._getOnMessageDelivered(); }, set onMessageDelivered(newOnMessageDelivered) { this._setOnMessageDelivered(newOnMessageDelivered); }, get onMessageArrived() { return this._getOnMessageArrived(); }, set onMessageArrived(newOnMessageArrived) { this._setOnMessageArrived(newOnMessageArrived); }, get trace() { return this._getTrace(); }, set trace(newTraceFunction) { this._setTrace(newTraceFunction); } }; /** * An application message, sent or received. * <p> * All attributes may be null, which implies the default values. * * @name Paho.MQTT.Message * @constructor * @param {String|ArrayBuffer} payload The message data to be sent. * <p> * @property {string} payloadString <i>read only</i> The payload as a string if the payload consists of valid UTF-8 characters. * @property {ArrayBuffer} payloadBytes <i>read only</i> The payload as an ArrayBuffer. * <p> * @property {string} destinationName <b>mandatory</b> The name of the destination to which the message is to be sent * (for messages about to be sent) or the name of the destination from which the message has been received. * (for messages received by the onMessage function). * <p> * @property {number} qos The Quality of Service used to deliver the message. * <dl> * <dt>0 Best effort (default). * <dt>1 At least once. * <dt>2 Exactly once. * </dl> * <p> * @property {Boolean} retained If true, the message is to be retained by the server and delivered * to both current and future subscriptions. * If false the server only delivers the message to current subscribers, this is the default for new Messages. * A received message has the retained boolean set to true if the message was published * with the retained boolean set to true * and the subscrption was made after the message has been published. * <p> * @property {Boolean} duplicate <i>read only</i> If true, this message might be a duplicate of one which has already been received. * This is only set on messages received from the server. * */ var Message = function (newPayload) { var payload; if ( typeof newPayload === "string" || newPayload instanceof ArrayBuffer || newPayload instanceof Int8Array || newPayload instanceof Uint8Array || newPayload instanceof Int16Array || newPayload instanceof Uint16Array || newPayload instanceof Int32Array || newPayload instanceof Uint32Array || newPayload instanceof Float32Array || newPayload instanceof Float64Array ) { payload = newPayload; } else { throw (format(ERROR.INVALID_ARGUMENT, [newPayload, "newPayload"])); } this._getPayloadString = function () { if (typeof payload === "string") return payload; else return parseUTF8(payload, 0, payload.length); }; this._getPayloadBytes = function() { if (typeof payload === "string") { var buffer = new ArrayBuffer(UTF8Length(payload)); var byteStream = new Uint8Array(buffer); stringToUTF8(payload, byteStream, 0); return byteStream; } else { return payload; }; }; var destinationName = undefined; this._getDestinationName = function() { return destinationName; }; this._setDestinationName = function(newDestinationName) { if (typeof newDestinationName === "string") destinationName = newDestinationName; else throw new Error(format(ERROR.INVALID_ARGUMENT, [newDestinationName, "newDestinationName"])); }; var qos = 0; this._getQos = function() { return qos; }; this._setQos = function(newQos) { if (newQos === 0 || newQos === 1 || newQos === 2 ) qos = newQos; else throw new Error("Invalid argument:"+newQos); }; var retained = false; this._getRetained = function() { return retained; }; this._setRetained = function(newRetained) { if (typeof newRetained === "boolean") retained = newRetained; else throw new Error(format(ERROR.INVALID_ARGUMENT, [newRetained, "newRetained"])); }; var duplicate = false; this._getDuplicate = function() { return duplicate; }; this._setDuplicate = function(newDuplicate) { duplicate = newDuplicate; }; }; Message.prototype = { get payloadString() { return this._getPayloadString(); }, get payloadBytes() { return this._getPayloadBytes(); }, get destinationName() { return this._getDestinationName(); }, set destinationName(newDestinationName) { this._setDestinationName(newDestinationName); }, get qos() { return this._getQos(); }, set qos(newQos) { this._setQos(newQos); }, get retained() { return this._getRetained(); }, set retained(newRetained) { this._setRetained(newRetained); }, get duplicate() { return this._getDuplicate(); }, set duplicate(newDuplicate) { this._setDuplicate(newDuplicate); } }; // Module contents. return { Client: Client, Message: Message }; })(window); var webduino = webduino || { version: '0.6.0' }; if (typeof exports !== 'undefined') { module.exports = webduino; } +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var DEBUG_STR = 'DEBUG_WEBDUINOJS'; function Logger(option) { if (!option) { option = '*'; } if (typeof option === 'string') { option = { key: option }; } this._option = option; this._key = option.key; this._isShow = isShow.bind(this); init.call(this); } function hasLocalStorage() { try { return !!localStorage; } catch (err) { return false; } } function hasProcess() { try { return !!process; } catch (err) { return false; } } function isShow() { var debugKeys = []; var debugStr; if (hasLocalStorage()) { debugStr = localStorage.getItem(DEBUG_STR); } if (hasProcess()) { debugStr = process.env[DEBUG_STR]; } if (debugStr) { debugKeys = debugStr.split(',').map(function (val) { return val.trim(); }); } if (debugStr && (debugKeys.indexOf('*') !== -1 || debugKeys.indexOf(this._key) !== -1)) { return true; } return false; } function init() { var self = this; var methodNames = ['log', 'info', 'warn', 'error']; var noop = function () { }; var isCopy = this._isShow(); methodNames.forEach(function (name) { if (isCopy) { self[name] = Function.prototype.bind.call(console[name], console); } else { self[name] = noop; } }); } scope.Logger = Logger; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; // source: // https://raw.githubusercontent.com/Gozala/events/master/events.js var proto; /** * An event emitter in browser. * * @namespace webduino * @class EventEmitter * @constructor */ function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } proto = EventEmitter.prototype; proto._events = undefined; proto._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. /** * Default maximum number of listeners (10). * * @property defaultMaxListeners * @type {Number} * @static */ EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. /** * Set maximum number of listeners that is allow to bind on an emitter. * * @method setMaxListeners * @param {Number} n Number of listeners. */ proto.setMaxListeners = function (n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; /** * Emit an event of certain type. * * @method emit * @param {String} type Event type. * @param {Object} [object,...] Event object(s). */ proto.emit = function (type) { var handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. // EDIT: Do not throw unhandled 'error' in the browser. (mz) // if (type === 'error') { // if (!this._events.error || // (isObject(this._events.error) && !this._events.error.length)) { // er = arguments[1]; // if (er instanceof Error) { // throw er; // Unhandled 'error' event // } // throw TypeError('Uncaught, unspecified "error" event.'); // } // } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; /** * Add a listener for a certain type of event. * * @method addListener * @param {String} type Event type. * @param {Function} listener Event listener. */ proto.addListener = function (type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; /** * Alias for EventEmitter.addListener(type, listener) * * @method on * @param {String} type Event type. * @param {Function} listener Event listener. */ proto.on = proto.addListener; /** * Add a one-time listener for a certain type of event. * * @method once * @param {String} type Event type. * @param {Function} listener Event listener. */ proto.once = function (type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; /** * Remove a listener for certain type of event. * * @method removeListener * @param {String} type Event type. * @param {Function} listener Event listener. */ // emits a 'removeListener' event iff the listener was removed proto.removeListener = function (type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; /** * Remove all listeners of certain type. * * @method removeAllListeners * @param {String} type Event type. */ proto.removeAllListeners = function (type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; /** * Return the listener list bound to certain type of event. * * @method listeners * @param {String} type Evnet type. */ proto.listeners = function (type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; /** * Count the number of listeners of an emitter. * * @method listenerCount * @param {webduino.EventEmitter} emitter The EventEmitter instance to count. * @param {String} type Event type. * @static */ EventEmitter.listenerCount = function (emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } scope.EventEmitter = EventEmitter; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var isBrowser = typeof exports === 'undefined'; var objProto = Object.prototype, toStr = objProto.toString; function isFn(value) { return typeof value === 'function'; } function isObject(value) { return '[object Object]' === toStr.call(value); } function isHash(value) { return isObject(value) && value.constructor === Object && !value.nodeType && !value.setInterval; } function isArray(value) { return Array.isArray(value); } // source: // https://github.com/dreamerslab/node.extend/blob/master/lib/extend.js function extend() { var target = arguments[0] || {}; var i = 1; var length = arguments.length; var deep = false; var options, name, src, copy, copy_is_array, clone; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== 'object' && !isFn(target)) { target = {}; } for (; i < length; i++) { // Only deal with non-null/undefined values options = arguments[i]; if (options !== null) { if (typeof options === 'string') { options = options.split(''); } // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (isHash(copy) || (copy_is_array = isArray(copy)))) { if (copy_is_array) { copy_is_array = false; clone = src && isArray(src) ? src : []; } else { clone = src && isHash(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { target[name] = copy; } } } } // Return the modified object return target; } function parseURL(str) { if (isBrowser) { var url = document.createElement('a'); url.href = str; return url; } else { return require('url').parse(str); } } function randomId() { return (Math.random() * Date.now()).toString(36).replace(/\./g, ''); } scope.util = { isFn: isFn, isFunction: isFn, isObject: isObject, isHash: isHash, isArray: isArray, extend: extend, parseURL: parseURL, randomId: randomId }; })); /* global Promise:true */ +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; if (typeof exports !== 'undefined' && typeof Promise === 'undefined') { Promise = require('es6-promise').Promise; } // source: // https://raw.githubusercontent.com/twistdigital/es6-promisify/release/2.0.0/lib/promisify.js // Promise Context object constructor. function Context(resolve, reject, custom) { this.resolve = resolve; this.reject = reject; this.custom = custom; } // Default callback function - rejects on truthy error, otherwise resolves function callback(ctx, err, result) { if (typeof ctx.custom === 'function') { var cust = function () { // Bind the callback to itself, so the resolve and reject // properties that we bound are available to the callback. // Then we push it onto the end of the arguments array. return ctx.custom.apply(cust, arguments); }; cust.resolve = ctx.resolve; cust.reject = ctx.reject; cust.call(null, err, result); } else { if (err) { return ctx.reject(err); } ctx.resolve(result); } } function promisify(original, custom) { return function () { // Store original context var that = this, args = Array.prototype.slice.call(arguments); // Return the promisified function return new Promise(function (resolve, reject) { // Create a Context object var ctx = new Context(resolve, reject, custom); // Append the callback bound to the context args.push(callback.bind(null, ctx)); // Call the function original.apply(that, args); }); }; } scope.util.promisify = promisify; })); /*eslint no-unused-vars: ["error", { "args": "none" }]*/ +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var EventEmitter = scope.EventEmitter, proto; var TransportEvent = { /** * Fires when a transport is opened. * * @event TransportEvent.OPEN */ OPEN: "open", /** * Fires when a transport receives a message. * * @event TransportEvent.MESSAGE */ MESSAGE: "message", /** * Fires when a transport get an error. * * @event TransportEvent.ERROR */ ERROR: "error", /** * Fires when a transport is closed. * * @event TransportEvent.CLOSE */ CLOSE: "close", /** * Fires when a transport is re-opened. * * @event TransportEvent.REOPEN */ REOPEN: "reopen" }; /** * A messaging mechanism to carry underlying firmata messages. This is an abstract class meant to be extended. * * @namespace webduino * @class Transport * @constructor * @param {Object} options Options to build the transport instance. * @extends webduino.EventEmitter */ function Transport(options) { EventEmitter.call(this); } Transport.prototype = proto = Object.create(EventEmitter.prototype, { constructor: { value: Transport }, /** * Indicates if the state of the transport is open. * * @attribute isOpen * @type {Boolean} * @readOnly */ isOpen: { value: false } }); /** * Send payload through the transport. * * @method send * @param {Array} payload The actual data to be sent. */ proto.send = function (payload) { throw new Error('direct call on abstract method.'); }; /** * Close and terminate the transport. * * @method close */ proto.close = function () { throw new Error('direct call on abstract method.'); }; /** * Flush any buffered data of the transport. * * @method flush */ proto.flush = function () { throw new Error('direct call on abstract method.'); }; scope.TransportEvent = TransportEvent; scope.Transport = Transport; scope.transport = scope.transport || {}; })); /* global webduino */ +(function (scope) { 'use strict'; var push = Array.prototype.push; var Transport = scope.Transport, TransportEvent = scope.TransportEvent, util = scope.util, proto; var STATUS = { OK: 'OK' }; var TOPIC = { PING: '/PING', PONG: '/PONG', STATUS: '/STATUS' }; /** * Conveying messages over MQTT protocol. * * @namespace webduino.transport * @class MqttTransport * @constructor * @param {Object} options Options to build a proper transport * @extends webduino.Transport */ function MqttTransport(options) { Transport.call(this, options); this._options = options; this._client = null; this._timer = null; this._sendTimer = null; this._buf = []; this._status = ''; this._connHandler = onConnect.bind(this); this._connFailedHandler = onConnectFailed.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); init(this); } function init(self) { self._client = new Paho.MQTT.Client(self._options.server, '_' + self._options.device + (self._options.multi ? '.' + util.randomId() : '') ); self._client.onMessageArrived = self._messageHandler; self._client.onConnectionLost = self._disconnHandler; self._client.onConnected = self._connHandler; self._client.connect({ userName: self._options.login || '', password: self._options.password || '', timeout: MqttTransport.CONNECT_TIMEOUT, keepAliveInterval: MqttTransport.KEEPALIVE_INTERVAL, onSuccess: self._connHandler, onFailure: self._connFailedHandler, reconnect: !!self._options.autoReconnect, reconnectInterval: MqttTransport.RECONNECT_PERIOD }); } function onConnect() { this._client.subscribe(this._options.device + TOPIC.PONG); this._client.subscribe(this._options.device + TOPIC.STATUS); } function onConnectFailed(respObj) { this.emit(TransportEvent.ERROR, new Error(respObj.errorMessage)); } function onMessage(message) { var dest = message.destinationName, oldStatus = this._status; switch (dest.substr(dest.lastIndexOf('/') + 1)) { case 'STATUS': this._status = message.payloadString; detectStatusChange(this, this._status, oldStatus); break; default: (this._status === STATUS.OK) && this.emit(TransportEvent.MESSAGE, message.payloadBytes); break; } } function detectStatusChange(self, newStatus, oldStatus) { if (newStatus === oldStatus) { if (newStatus === STATUS.OK) { // Device reconnected self.emit(TransportEvent.REOPEN); } return; } if (newStatus === STATUS.OK) { self.emit(TransportEvent.OPEN); } else { self.emit(TransportEvent.ERROR, new Error('board connection failed.')); } } function onDisconnect(respObj) { if (!respObj.errorCode || !respObj.reconnect) { delete this._client; respObj.errorCode && this.emit(TransportEvent.ERROR, new Error(respObj.errorMessage)); this.emit(TransportEvent.CLOSE); } } function sendOut() { var payload = new Paho.MQTT.Message(new Uint8Array(this._buf).buffer); payload.destinationName = this._options.device + TOPIC.PING; payload.qos = 0; this.isOpen && this._client.send(payload); clearBuf(this); } function clearBuf(self) { self._buf = []; clearImmediate(self._sendTimer); self._sendTimer = null; } MqttTransport.prototype = proto = Object.create(Transport.prototype, { constructor: { value: MqttTransport }, isOpen: { get: function () { return this._client && this._client.isConnected(); } } }); proto.send = function (payload) { if (this._buf.length + payload.length + this._options.device.length + TOPIC.PING.length + 4 > MqttTransport.MAX_PACKET_SIZE) { this._sendOutHandler(); } push.apply(this._buf, payload); if (!this._sendTimer) { this._sendTimer = setImmediate(this._sendOutHandler); } }; proto.close = function () { if (this._client) { if (this._client.isConnected()) { this._client.disconnect(); } else { delete this._client; } } }; proto.flush = function () { if (this._buf && this._buf.length) { this._sendOutHandler(); } }; /** * Reconnect period when MQTT connection goes down. Measured in seconds. * * @property RECONNECT_PERIOD * @type {Number} * @static */ MqttTransport.RECONNECT_PERIOD = 1; /** * MQTT keepalive interval. Measured in seconds. * * @property KEEPALIVE_INTERVAL * @type {Number} * @static */ MqttTransport.KEEPALIVE_INTERVAL = 15; /** * Time to wait before throwing connection timeout exception. Measured in seconds. * * @property CONNECT_TIMEOUT * @type {Number} * @static */ MqttTransport.CONNECT_TIMEOUT = 30; /** * Maximum packet size in KB. * * @property MAX_PACKET_SIZE * @type {Number} * @static */ MqttTransport.MAX_PACKET_SIZE = 128; scope.transport.mqtt = MqttTransport; }(webduino)); /* global webduino */ +(function (scope) { 'use strict'; var push = Array.prototype.push, WebSocketClient = WebSocket; var Transport = scope.Transport, TransportEvent = scope.TransportEvent, proto; function WebSocketTransport(options) { Transport.call(this, options); this._options = options; this._client = null; this._sendTimer = null; this._buf = []; this._connHandler = onConnect.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); this._errorHandler = onError.bind(this); init(this); } function init(self) { var url = self._options.url; self._options.url = url.indexOf('ws://') === 0 ? url : 'ws://' + url; self._client = new WebSocketClient(self._options.url); self._client.binaryType = 'arraybuffer'; self._client.onopen = self._connHandler; self._client.onmessage = self._messageHandler; self._client.onclose = self._disconnHandler; self._client.onerror = self._errorHandler; } function onConnect(event) { this.emit(TransportEvent.OPEN, event); } function onMessage(event) { this.emit(TransportEvent.MESSAGE, new Uint8Array(event.data)); } function onDisconnect(event) { delete this._client; this.emit(TransportEvent.CLOSE, event); } function onError(event) { this.emit(TransportEvent.ERROR, event); } function sendOut() { var payload = new Uint8Array(this._buf).buffer; this.isOpen && this._client.send(payload); clearBuf(this); } function clearBuf(self) { self._buf = []; clearImmediate(self._sendTimer); self._sendTimer = null; } WebSocketTransport.prototype = proto = Object.create(Transport.prototype, { constructor: { value: WebSocketTransport }, isOpen: { get: function () { return this._client && this._client.readyState === WebSocketClient.OPEN; } } }); proto.send = function (payload) { if (this._buf.length + payload.length > WebSocketTransport.MAX_PACKET_SIZE) { this._sendOutHandler(); } push.apply(this._buf, payload); if (!this._sendTimer) { this._sendTimer = setImmediate(this._sendOutHandler); } }; proto.close = function () { if (this._client) { if (this._client.readyState === WebSocketClient.OPEN) { this._client.close(); } else { delete this._client; } } }; proto.flush = function () { if (this._buf && this._buf.length) { this._sendOutHandler(); } }; WebSocketTransport.MAX_PACKET_SIZE = 64; scope.transport.websocket = WebSocketTransport; }(webduino)); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var EventEmitter = scope.EventEmitter, proto; var PinEvent = { CHANGE: 'change', RISING_EDGE: 'risingEdge', FALLING_EDGE: 'fallingEdge' }; function Pin(board, number, type) { EventEmitter.call(this); this._board = board; this._type = type; this._capabilities = {}; this._number = number; this._analogNumber = undefined; this._analogWriteResolution = 255; // default this._analogReadResolution = 1023; // default this._value = 0; this._lastValue = -1; this._preFilterValue = 0; this._average = 0; this._minimum = Math.pow(2, 16); this._maximum = 0; this._sum = 0; this._numSamples = 0; this._filters = null; this._generator = null; this._state = undefined; this._analogReporting = false; this._sendOutHandler = sendOut.bind(this); this._autoSetValueCallback = this.autoSetValue.bind(this); managePinListener(this); } function managePinListener(self) { var type = self._type; if (type === Pin.DOUT || type === Pin.AOUT || type === Pin.SERVO) { if (!EventEmitter.listenerCount(self, PinEvent.CHANGE)) { self.on(PinEvent.CHANGE, self._sendOutHandler); } } else { if (EventEmitter.listenerCount(self, PinEvent.CHANGE)) { try { self.removeListener(PinEvent.CHANGE, self._sendOutHandler); } catch (e) { // Pin had reference to other handler, ignore console.error('debug: caught self removeEventListener exception'); } } } } function sendOut(self) { var type = self._type, pinNum = self._number, board = self._board, value = self.value; switch (type) { case Pin.DOUT: board.sendDigitalData(pinNum, value); break; case Pin.AOUT: board.sendAnalogData(pinNum, value); break; case Pin.SERVO: board.sendServoData(pinNum, value); break; } } Pin.prototype = proto = Object.create(EventEmitter.prototype, { constructor: { value: Pin }, capabilities: { get: function () { return this._capabilities; } }, analogNumber: { get: function () { return this._analogNumber; } }, number: { get: function () { return this._number; } }, analogWriteResolution: { get: function () { return this._analogWriteResolution; } }, analogReadResolution: { get: function () { return this._analogReadResolution; } }, state: { get: function () { return this._state; }, set: function (val) { if (this._type === Pin.PWM) { val = val / this._analogWriteResolution; } this.value = this._value = this._state = val; } }, type: { get: function () { return this._type; } }, average: { get: function () { return this._average; } }, minimum: { get: function () { return this._minimum; } }, maximum: { get: function () { return this._maximum; } }, value: { get: function () { return this._value; }, set: function (val) { this._lastValue = this._value; this._preFilterValue = val; this._value = this.applyFilters(val); this.calculateMinMaxAndMean(this._value); this.detectChange(this._lastValue, this._value); } }, lastValue: { get: function () { return this._lastValue; } }, preFilterValue: { get: function () { return this._preFilterValue; } }, filters: { get: function () { return this._filters; }, set: function (filters) { this._filters = filters; } }, generator: { get: function () { return this._generator; } } }); proto.setAnalogNumber = function (num) { this._analogNumber = num; }; proto.setAnalogWriteResolution = function (value) { this._analogWriteResolution = value; }; proto.setAnalogReadResolution = function (value) { this._analogReadResolution = value; }; proto.setCapabilities = function (capabilities) { this._capabilities = capabilities; var analogWriteRes = this._capabilities[Pin.PWM]; var analogReadRes = this._capabilities[Pin.AIN]; if (analogWriteRes) { this._analogWriteResolution = Math.pow(2, analogWriteRes) - 1; } if (analogReadRes) { this._analogReadResolution = Math.pow(2, analogReadRes) - 1; } }; proto.setMode = function (mode, silent) { var pinNum = this._number, board = this._board; if (mode >= 0 && mode < Pin.TOTAL_PIN_MODES) { this._type = mode; managePinListener(this); if (!silent || silent !== true) { board.setPinMode(pinNum, mode); } } }; proto.detectChange = function (oldValue, newValue) { if (oldValue === newValue) { return; } this.emit(PinEvent.CHANGE, this); if (oldValue <= 0 && newValue !== 0) { this.emit(PinEvent.RISING_EDGE, this); } else if (oldValue !== 0 && newValue <= 0) { this.emit(PinEvent.FALLING_EDGE, this); } }; proto.clearWeight = function () { this._sum = this._average; this._numSamples = 1; }; proto.calculateMinMaxAndMean = function (val) { var MAX_SAMPLES = Number.MAX_VALUE; this._minimum = Math.min(val, this._minimum); this._maximum = Math.max(val, this._maximum); this._sum += val; this._average = this._sum / (++this._numSamples); if (this._numSamples >= MAX_SAMPLES) { this.clearWeight(); } }; proto.clear = function () { this._minimum = this._maximum = this._average = this._lastValue = this._preFilterValue; this.clearWeight(); }; proto.addFilter = function (newFilter) { if (newFilter === null) { return; } if (this._filters === null) { this._filters = []; } this._filters.push(newFilter); }; proto.removeFilter = function (filterToRemove) { var index; if (this._filters.length < 1) { return; } index = this._filters.indexOf(filterToRemove); if (index !== -1) { this._filters.splice(index, 1); } }; proto.addGenerator = function (newGenerator) { this.removeGenerator(); this._generator = newGenerator; this._generator.on('update', this._autoSetValueCallback); }; proto.removeGenerator = function () { if (this._generator !== null) { this._generator.removeListener('update', this._autoSetValueCallback); } delete this._generator; }; proto.removeAllFilters = function () { delete this._filters; }; proto.autoSetValue = function (val) { this.value = val; }; proto.applyFilters = function (val) { var result; if (this._filters === null) { return val; } result = val; var len = this._filters.length; for (var i = 0; i < len; i++) { result = this._filters[i].processSample(result); } return result; }; proto.read = function () { var type = this._type, board = this._board, self = this; switch (type) { case Pin.DOUT: case Pin.AOUT: case Pin.SERVO: return board.queryPinState(self._number).then(function (pin) { return pin.state; }); case Pin.AIN: if (!self._analogReporting) { board.enableAnalogPin(self._analogNumber); } return new Promise(function (resolve) { setImmediate(function () { resolve(self.value); }); }); case Pin.DIN: return new Promise(function (resolve) { setImmediate(function () { resolve(self.value); }); }); } }; proto.write = function (value) { var type = this._type; if (type === Pin.DOUT || type === Pin.AOUT || type === Pin.SERVO) { this.value = value; } }; Pin.HIGH = 1; Pin.LOW = 0; Pin.ON = 1; Pin.OFF = 0; Pin.DIN = 0x00; Pin.DOUT = 0x01; Pin.AIN = 0x02; Pin.AOUT = 0x03; Pin.PWM = 0x03; Pin.SERVO = 0x04; Pin.SHIFT = 0x05; Pin.I2C = 0x06; Pin.ONEWIRE = 0x07; Pin.STEPPER = 0x08; Pin.TOTAL_PIN_MODES = 9; scope.PinEvent = PinEvent; scope.Pin = Pin; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var EventEmitter = scope.EventEmitter; /** * A component to be attached to a board. This is an abstract class meant to be extended. * * @namespace webduino * @class Module * @constructor * @extends webduino.EventEmitter */ function Module() { EventEmitter.call(this); } Module.prototype = Object.create(EventEmitter.prototype, { constructor: { value: Module }, /** * Type of the module. * * @attribute type * @type {String} * @readOnly */ type: { get: function () { return this._type; } } }); scope.Module = Module; scope.module = scope.module || {}; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var push = Array.prototype.push; var EventEmitter = scope.EventEmitter, TransportEvent = scope.TransportEvent, Logger = scope.Logger, Pin = scope.Pin, util = scope.util, proto; var BoardEvent = { ANALOG_DATA: 'analogData', DIGITAL_DATA: 'digitalData', FIRMWARE_VERSION: 'firmwareVersion', FIRMWARE_NAME: 'firmwareName', STRING_MESSAGE: 'stringMessage', SYSEX_MESSAGE: 'sysexMessage', PIN_STATE_RESPONSE: 'pinStateResponse', READY: 'ready', ERROR: 'error', BEFOREDISCONNECT: 'beforeDisconnect', DISCONNECT: 'disconnect', RECONNECT: 'reconnect' }; /** * Message command bytes (128-255/0x80-0xFF) * https://github.com/firmata/protocol/blob/master/protocol.md */ var DIGITAL_MESSAGE = 0x90, ANALOG_MESSAGE = 0xE0, REPORT_ANALOG = 0xC0, REPORT_DIGITAL = 0xD0, SET_PIN_MODE = 0xF4, REPORT_VERSION = 0xF9, SYSEX_RESET = 0xFF, START_SYSEX = 0xF0, END_SYSEX = 0xF7; // Extended command set using sysex (0-127/0x00-0x7F) var SERVO_CONFIG = 0x70, STRING_DATA = 0x71, // SHIFT_DATA = 0x75, // I2C_REQUEST = 0x76, // I2C_REPLY = 0x77, // I2C_CONFIG = 0x78, EXTENDED_ANALOG = 0x6F, PIN_STATE_QUERY = 0x6D, PIN_STATE_RESPONSE = 0x6E, CAPABILITY_QUERY = 0x6B, CAPABILITY_RESPONSE = 0x6C, ANALOG_MAPPING_QUERY = 0x69, ANALOG_MAPPING_RESPONSE = 0x6A, REPORT_FIRMWARE = 0x79, SAMPLING_INTERVAL = 0x7A; // SYSEX_NON_REALTIME = 0x7E, // SYSEX_REALTIME = 0x7F; /** * An abstract development board. * * @namespace webduino * @class Board * @constructor * @param {Object} options Options to build the board instance. * @extends webduino.EventEmitter */ function Board(options) { EventEmitter.call(this); this._options = options; this._buf = []; this._digitalPort = []; this._numPorts = 0; this._analogPinMapping = []; this._digitalPinMapping = []; this._i2cPins = []; this._ioPins = []; this._totalPins = 0; this._totalAnalogPins = 0; this._samplingInterval = 19; this._isReady = false; this._firmwareName = ''; this._firmwareVersion = 0; this._capabilityQueryResponseReceived = false; this._numPinStateRequests = 0; this._numDigitalPortReportRequests = 0; this._transport = null; this._pinStateEventCenter = new EventEmitter(); this._logger = new Logger('Board'); this._sendingInterval = 0; this._sendingRec = []; this._initialVersionResultHandler = onInitialVersionResult.bind(this); this._openHandler = onOpen.bind(this); this._reOpenHandler = onReOpen.bind(this); this._messageHandler = onMessage.bind(this); this._errorHandler = onError.bind(this); this._closeHandler = onClose.bind(this); this._cleanupHandler = cleanup.bind(this); attachCleanup(this); this._setTransport(this._options.transport); } function onInitialVersionResult(event) { var version = event.version * 10; if (version >= 23) { // TODO: do reset and handle response // this.systemReset(); this.queryCapabilities(); } else { throw new Error('You must upload StandardFirmata version 2.3 ' + 'or greater from Arduino version 1.0 or higher'); } } function onOpen() { this._logger.info('onOpen', 'Device online'); this.begin(); } function onReOpen() { this._logger.info("onReOpen", "Device re-online"); this.emit(BoardEvent.RECONNECT); } function onMessage(data) { try { this._logger.info('onMessage', data); var len = data.length; if (len) { for (var i = 0; i < len; i++) { this.processInput(data[i]); } } else { this.processInput(data); } } catch (err) { console.error(err); throw err; } } function onError(error) { this._logger.warn('onError', error); this._isReady = false; this.emit(BoardEvent.ERROR, error); setImmediate(this.disconnect.bind(this)); } function onClose() { this._isReady = false; this._transport.removeAllListeners(); delete this._transport; this.emit(BoardEvent.DISCONNECT); } function cleanup() { this.disconnect(); } function attachCleanup(self) { if (typeof exports === 'undefined') { window.addEventListener('beforeunload', self._cleanupHandler); } else { process.addListener('uncaughtException', self._cleanupHandler); } } function unattachCleanup(self) { if (typeof exports === 'undefined') { window.removeEventListener('beforeunload', self._cleanupHandler); } else { process.removeListener('uncaughtException', self._cleanupHandler); } } Board.prototype = proto = Object.create(EventEmitter.prototype, { constructor: { value: Board }, samplingInterval: { get: function () { return this._samplingInterval; }, set: function (interval) { if (interval >= Board.MIN_SAMPLING_INTERVAL && interval <= Board.MAX_SAMPLING_INTERVAL) { this._samplingInterval = interval; this.send([ START_SYSEX, SAMPLING_INTERVAL, interval & 0x007F, (interval >> 7) & 0x007F, END_SYSEX ]); } else { throw new Error('warning: Sampling interval must be between ' + Board.MIN_SAMPLING_INTERVAL + ' and ' + Board.MAX_SAMPLING_INTERVAL); } } }, sendingInterval: { get: function () { return this._sendingInterval; }, set: function (interval) { if (typeof interval !== 'number') return; this._sendingInterval = interval < 0 ? 0: interval; } }, isReady: { get: function () { return this._isReady; } }, isConnected: { get: function () { return this._transport && this._transport.isOpen; } } }); proto.begin = function () { this.once(BoardEvent.FIRMWARE_NAME, this._initialVersionResultHandler); this.reportFirmware(); }; proto.processInput = function (inputData) { var len, cmd; this._buf.push(inputData); len = this._buf.length; cmd = this._buf[0]; if (cmd >= 128 && cmd !== START_SYSEX) { if (len === 3) { this.processMultiByteCommand(this._buf); this._buf = []; } } else if (cmd === START_SYSEX && inputData === END_SYSEX) { this.processSysexCommand(this._buf); this._buf = []; } else if (inputData >= 128 && cmd < 128) { this._buf = []; if (inputData !== END_SYSEX) { this._buf.push(inputData); } } }; proto.processMultiByteCommand = function (commandData) { var command = commandData[0], channel; if (command < 0xF0) { command = command & 0xF0; channel = commandData[0] & 0x0F; } switch (command) { case DIGITAL_MESSAGE: this._logger.info('processMultiByteCommand digital:', channel, commandData[1], commandData[2]); this._options.handleDigitalPins && this.processDigitalMessage(channel, commandData[1], commandData[2]); break; case REPORT_VERSION: this._firmwareVersion = commandData[1] + commandData[2] / 10; this.emit(BoardEvent.FIRMWARE_VERSION, { version: this._firmwareVersion }); break; case ANALOG_MESSAGE: this._logger.info('processMultiByteCommand analog:', channel, commandData[1], commandData[2]); this.processAnalogMessage(channel, commandData[1], commandData[2]); break; } }; proto.processDigitalMessage = function (port, bits0_6, bits7_13) { var offset = port * 8, lastPin = offset + 8, portVal = bits0_6 | (bits7_13 << 7), pinVal, pin = {}; if (lastPin >= this._totalPins) { lastPin = this._totalPins; } var j = 0; for (var i = offset; i < lastPin; i++) { pin = this.getDigitalPin(i); if (pin === undefined) { return; } if (pin.type === Pin.DIN) { pinVal = (portVal >> j) & 0x01; if (pinVal !== pin.value) { pin.value = pinVal; this.emit(BoardEvent.DIGITAL_DATA, { pin: pin }); } } j++; } if (!this._isReady) { this._numDigitalPortReportRequests--; if (0 >= this._numDigitalPortReportRequests) { this.startup(); } } }; proto.processAnalogMessage = function (channel, bits0_6, bits7_13) { var analogPin = this.getAnalogPin(channel); if (analogPin === undefined) { return; } analogPin.value = this.getValueFromTwo7bitBytes(bits0_6, bits7_13) / analogPin.analogReadResolution; if (analogPin.value !== analogPin.lastValue) { if (this._isReady) { analogPin._analogReporting = true; } this.emit(BoardEvent.ANALOG_DATA, { pin: analogPin }); } }; proto.processSysexCommand = function (sysexData) { sysexData.shift(); sysexData.pop(); var command = sysexData[0]; switch (command) { case REPORT_FIRMWARE: this.processQueryFirmwareResult(sysexData); break; case STRING_DATA: this.processSysExString(sysexData); break; case CAPABILITY_RESPONSE: this.processCapabilitiesResponse(sysexData); break; case PIN_STATE_RESPONSE: this.processPinStateResponse(sysexData); break; case ANALOG_MAPPING_RESPONSE: this.processAnalogMappingResponse(sysexData); break; default: this.emit(BoardEvent.SYSEX_MESSAGE, { message: sysexData }); break; } }; proto.processQueryFirmwareResult = function (msg) { var data; for (var i = 3, len = msg.length; i < len; i += 2) { data = msg[i]; data += msg[i + 1]; this._firmwareName += String.fromCharCode(data); } this._firmwareVersion = msg[1] + msg[2] / 10; this.emit(BoardEvent.FIRMWARE_NAME, { name: this._firmwareName, version: this._firmwareVersion }); }; proto.processSysExString = function (msg) { var str = '', data, len = msg.length; for (var i = 1; i < len; i += 2) { data = msg[i]; data += msg[i + 1]; str += String.fromCharCode(data); } this.emit(BoardEvent.STRING_MESSAGE, { message: str }); }; proto.processCapabilitiesResponse = function (msg) { var pinCapabilities = {}, byteCounter = 1, pinCounter = 0, analogPinCounter = 0, len = msg.length, type, pin; this._capabilityQueryResponseReceived = true; while (byteCounter <= len) { if (msg[byteCounter] === 127) { this._digitalPinMapping[pinCounter] = pinCounter; type = undefined; if (pinCapabilities[Pin.DOUT]) { type = Pin.DOUT; } if (pinCapabilities[Pin.AIN]) { type = Pin.AIN; this._analogPinMapping[analogPinCounter++] = pinCounter; } pin = new Pin(this, pinCounter, type); pin.setCapabilities(pinCapabilities); this._ioPins[pinCounter] = pin; if (pin._capabilities[Pin.I2C]) { this._i2cPins.push(pin.number); } pinCapabilities = {}; pinCounter++; byteCounter++; } else { pinCapabilities[msg[byteCounter]] = msg[byteCounter + 1]; byteCounter += 2; } } this._numPorts = Math.ceil(pinCounter / 8); for (var j = 0; j < this._numPorts; j++) { this._digitalPort[j] = 0; } this._totalPins = pinCounter; this._totalAnalogPins = analogPinCounter; this.queryAnalogMapping(); }; proto.processAnalogMappingResponse = function (msg) { var len = msg.length; for (var i = 1; i < len; i++) { if (msg[i] !== 127) { this._analogPinMapping[msg[i]] = i - 1; this.getPin(i - 1).setAnalogNumber(msg[i]); } } if (!this._isReady) { if (this._options.initialReset) { this.systemReset(); } if (this._options.handleDigitalPins) { this.enableDigitalPins(); } else { this.startup(); } } }; proto.startup = function () { this._logger.info('startup', 'Board Ready'); this._isReady = true; this.emit(BoardEvent.READY, this); }; proto.systemReset = function () { this.send([SYSEX_RESET]); }; proto.processPinStateResponse = function (msg) { if (this._numPinStateRequests <= 0) { return; } var len = msg.length, pinNum = msg[1], pinType = msg[2], pinState, pin = this._ioPins[pinNum]; if (len > 4) { pinState = this.getValueFromTwo7bitBytes(msg[3], msg[4]); } else if (len > 3) { pinState = msg[3]; } if (pin.type !== pinType) { pin.setMode(pinType, true); } pin.state = pinState; this._numPinStateRequests--; if (this._numPinStateRequests < 0) { this._numPinStateRequests = 0; } this._pinStateEventCenter.emit(pinNum, pin); this.emit(BoardEvent.PIN_STATE_RESPONSE, { pin: pin }); }; proto.toDec = function (ch) { ch = ch.substring(0, 1); var decVal = ch.charCodeAt(0); return decVal; }; proto.sendAnalogData = function (pin, value) { var pwmResolution = this.getDigitalPin(pin).analogWriteResolution; value *= pwmResolution; value = (value < 0) ? 0 : value; value = (value > pwmResolution) ? pwmResolution : value; if (pin > 15 || value > Math.pow(2, 14)) { this.sendExtendedAnalogData(pin, value); } else { this.send([ANALOG_MESSAGE | (pin & 0x0F), value & 0x007F, (value >> 7) & 0x007F]); } }; proto.sendExtendedAnalogData = function (pin, value) { var analogData = []; // If > 16 bits if (value > Math.pow(2, 16)) { throw new Error('Extended Analog values > 16 bits are not currently supported by StandardFirmata'); } analogData[0] = START_SYSEX; analogData[1] = EXTENDED_ANALOG; analogData[2] = pin; analogData[3] = value & 0x007F; analogData[4] = (value >> 7) & 0x007F; // Up to 14 bits // If > 14 bits if (value >= Math.pow(2, 14)) { analogData[5] = (value >> 14) & 0x007F; } analogData.push(END_SYSEX); this.send(analogData); }; proto.sendDigitalData = function (pin, value) { try { var portNum = Math.floor(pin / 8); if (value === Pin.HIGH) { // Set the bit this._digitalPort[portNum] |= (value << (pin % 8)); } else if (value === Pin.LOW) { // Clear the bit this._digitalPort[portNum] &= ~(1 << (pin % 8)); } else { // Should not happen... throw new Error('Invalid value passed to sendDigital, value must be 0 or 1.'); } this.sendDigitalPort(portNum, this._digitalPort[portNum]); } catch (err) { console.error('Board -> sendDigitalData, msg:', err.message, 'value:', value); this.emit(BoardEvent.ERROR, err); setImmediate(this.disconnect.bind(this)); } }; proto.sendServoData = function (pin, value) { var servoPin = this.getDigitalPin(pin); if (servoPin.type === Pin.SERVO && servoPin.lastValue !== value) { this.sendAnalogData(pin, value); } }; proto.queryCapabilities = function () { this._logger.info('queryCapabilities'); this.send([START_SYSEX, CAPABILITY_QUERY, END_SYSEX]); }; proto.queryAnalogMapping = function () { this._logger.info('queryAnalogMapping'); this.send([START_SYSEX, ANALOG_MAPPING_QUERY, END_SYSEX]); }; proto.getValueFromTwo7bitBytes = function (lsb, msb) { return (msb << 7) | lsb; }; proto.getTransport = function () { return this._transport; }; proto._setTransport = function (trsp) { var klass = trsp; if (typeof trsp === 'string') { klass = scope.transport[trsp]; } if (klass && (trsp = new klass(this._options))) { trsp.on(TransportEvent.OPEN, this._openHandler); trsp.on(TransportEvent.MESSAGE, this._messageHandler); trsp.on(TransportEvent.ERROR, this._errorHandler); trsp.on(TransportEvent.CLOSE, this._closeHandler); trsp.on(TransportEvent.REOPEN, this._reOpenHandler); this._transport = trsp; } }; proto.reportVersion = function () { this.send(REPORT_VERSION); }; proto.reportFirmware = function () { this._logger.info('reportFirmware'); this.send([START_SYSEX, REPORT_FIRMWARE, END_SYSEX]); }; proto.enableDigitalPins = function () { this._logger.info('enableDigitalPins'); for (var i = 0; i < this._numPorts; i++) { this.sendDigitalPortReporting(i, Pin.ON); } }; proto.disableDigitalPins = function () { for (var i = 0; i < this._numPorts; i++) { this.sendDigitalPortReporting(i, Pin.OFF); } }; proto.sendDigitalPortReporting = function (port, mode) { if (!this._isReady) { this._numDigitalPortReportRequests++; } this.send([(REPORT_DIGITAL | port), mode]); }; proto.enableAnalogPin = function (pinNum) { this.sendAnalogPinReporting(pinNum, Pin.ON); this.getAnalogPin(pinNum)._analogReporting = true; }; proto.disableAnalogPin = function (pinNum) { this.sendAnalogPinReporting(pinNum, Pin.OFF); this.getAnalogPin(pinNum)._analogReporting = false; }; proto.sendAnalogPinReporting = function (pinNum, mode) { this.send([REPORT_ANALOG | pinNum, mode]); }; proto.setDigitalPinMode = function (pinNum, mode, silent) { this.getDigitalPin(pinNum).setMode(mode, silent); }; proto.setAnalogPinMode = function (pinNum, mode, silent) { this.getAnalogPin(pinNum).setMode(mode, silent); }; proto.setPinMode = function (pinNum, mode) { this.send([SET_PIN_MODE, pinNum, mode]); }; proto.enablePullUp = function (pinNum) { this.sendDigitalData(pinNum, Pin.HIGH); }; proto.getFirmwareName = function () { return this._firmwareName; }; proto.getFirmwareVersion = function () { return this._firmwareVersion; }; proto.getPinCapabilities = function () { var capabilities = [], len, pinElements, pinCapabilities, hasCapabilities; var modeNames = { 0: 'input', 1: 'output', 2: 'analog', 3: 'pwm', 4: 'servo', 5: 'shift', 6: 'i2c', 7: 'onewire', 8: 'stepper' }; len = this._ioPins.length; for (var i = 0; i < len; i++) { pinElements = {}; pinCapabilities = this._ioPins[i]._capabilities; hasCapabilities = false; for (var mode in pinCapabilities) { if (pinCapabilities.hasOwnProperty(mode)) { hasCapabilities = true; if (mode >= 0) { pinElements[modeNames[mode]] = this._ioPins[i]._capabilities[mode]; } } } if (!hasCapabilities) { capabilities[i] = { 'not available': '0' }; } else { capabilities[i] = pinElements; } } return capabilities; }; proto.queryPinState = function (pins, callback) { var self = this, promises = [], cmds = [], done; done = self._pinStateEventCenter.once.bind(self._pinStateEventCenter); pins = util.isArray(pins) ? pins : [pins]; pins = pins.map(function (pin) { return pin instanceof Pin ? pin : self.getPin(pin); }); pins.forEach(function (pin) { promises.push(util.promisify(done, function (pin) { this.resolve(pin); })(pin.number)); push.apply(cmds, [START_SYSEX, PIN_STATE_QUERY, pin.number, END_SYSEX]); self._numPinStateRequests++; }); self.send(cmds); if (typeof callback === 'function') { Promise.all(promises).then(function (pins) { callback.call(self, pins.length > 1 ? pins : pins[0]); }); } else { return pins.length > 1 ? promises : promises[0]; } }; proto.sendDigitalPort = function (portNumber, portData) { this.send([DIGITAL_MESSAGE | (portNumber & 0x0F), portData & 0x7F, portData >> 7]); }; proto.sendString = function (str) { var decValues = []; for (var i = 0, len = str.length; i < len; i++) { decValues.push(this.toDec(str[i]) & 0x007F); decValues.push((this.toDec(str[i]) >> 7) & 0x007F); } this.sendSysex(STRING_DATA, decValues); }; proto.sendSysex = function (command, data) { var sysexData = []; sysexData[0] = START_SYSEX; sysexData[1] = command; for (var i = 0, len = data.length; i < len; i++) { sysexData.push(data[i]); } sysexData.push(END_SYSEX); this.send(sysexData); }; proto.sendServoAttach = function (pin, minPulse, maxPulse) { var servoPin, servoData = []; minPulse = minPulse || 544; // Default value = 544 maxPulse = maxPulse || 2400; // Default value = 2400 servoData[0] = START_SYSEX; servoData[1] = SERVO_CONFIG; servoData[2] = pin; servoData[3] = minPulse % 128; servoData[4] = minPulse >> 7; servoData[5] = maxPulse % 128; servoData[6] = maxPulse >> 7; servoData[7] = END_SYSEX; this.send(servoData); servoPin = this.getDigitalPin(pin); servoPin.setMode(Pin.SERVO, true); }; proto.getPin = function (pinNum) { return this._ioPins[pinNum]; }; proto.getAnalogPin = function (pinNum) { return this._ioPins[this._analogPinMapping[pinNum]]; }; proto.getDigitalPin = function (pinNum) { return this._ioPins[this._digitalPinMapping[pinNum]]; }; proto.getPins = function () { return this._ioPins; }; proto.analogToDigital = function (analogPinNum) { return this.getAnalogPin(analogPinNum).number; }; proto.getPinCount = function () { return this._totalPins; }; proto.getAnalogPinCount = function () { return this._totalAnalogPins; }; proto.getI2cPins = function () { return this._i2cPins; }; proto.reportCapabilities = function () { var capabilities = this.getPinCapabilities(), len = capabilities.length, resolution; for (var i = 0; i < len; i++) { this._logger.info('reportCapabilities, Pin ' + i); for (var mode in capabilities[i]) { if (capabilities[i].hasOwnProperty(mode)) { resolution = capabilities[i][mode]; this._logger.info('reportCapabilities', '\t' + mode + ' (' + resolution + (resolution > 1 ? ' bits)' : ' bit)')); } } } }; proto.send = function (data) { if (!this.isConnected) return; if (this.sendingInterval === 0) { this._transport.send(data); return; } var idx = this._sendingRec.findIndex(function (val) { return val.value.toString() === data.toString(); }); if (idx !== -1) { if (Date.now() - this._sendingRec[idx].timestamp < this.sendingInterval) return; this._sendingRec.splice(idx, 1); } this._sendingRec.splice(0); this._sendingRec.push({ value: data.slice(), timestamp: Date.now() }); this._transport.send(data); }; proto.close = function (callback) { this.disconnect(callback); }; proto.flush = function () { this.isConnected && this._transport.flush(); }; proto.disconnect = function (callback) { callback = callback || function () {}; if (this.isConnected) { this.emit(BoardEvent.BEFOREDISCONNECT); } this._isReady = false; unattachCleanup(this); if (this._transport) { if (this._transport.isOpen) { this.once(BoardEvent.DISCONNECT, callback); this._transport.close(); } else { this._transport.removeAllListeners(); delete this._transport; callback(); } } else { callback(); } }; Board.MIN_SAMPLING_INTERVAL = 20; Board.MAX_SAMPLING_INTERVAL = 15000; scope.BoardEvent = BoardEvent; scope.Board = Board; scope.board = scope.board || {}; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var util = scope.util, TransportEvent = scope.TransportEvent, Board = scope.Board, proto; function WebArduino(options) { if (typeof options === 'string') { options = { device: options }; } if (options.area === 'china') { options.server = WebArduino.SERVER_CHINA; } options = util.extend(getDefaultOptions(), options); options.server = parseServer(options.server); Board.call(this, options); } function getDefaultOptions() { return { transport: 'mqtt', server: WebArduino.DEFAULT_SERVER, login: 'admin', password: 'password', autoReconnect: false, multi: false, initialReset: true, handleDigitalPins: true }; } function parseServer(url) { if (url.indexOf('://') === -1) { url = (typeof location !== 'undefined' && location.protocol === 'https:' ? 'wss:' : 'ws:') + '//' + url; } url = util.parseURL(url); return url.protocol + '//' + url.host + '/'; } WebArduino.prototype = proto = Object.create(Board.prototype, { constructor: { value: WebArduino } }); proto.reportFirmware = function () { var msg = [ 240, 121, 2, 4, 119, 0, 101, 0, 98, 0, 100, 0, 117, 0, 105, 0, 110, 0, 111, 0, 46, 0, 105, 0, 110, 0, 111, 0, 247 ]; mockMessageEvent(this, msg); }; proto.queryCapabilities = function () { var msg = [ 240, 108, 127, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 2, 10, 4, 14, 127, 0, 1, 1, 1, 2, 10, 4, 14, 127, 0, 1, 1, 1, 2, 10, 4, 14, 127, 0, 1, 1, 1, 2, 10, 4, 14, 127, 0, 1, 1, 1, 2, 10, 4, 14, 127, 0, 1, 1, 1, 2, 10, 4, 14, 127, 2, 10, 127, 2, 10, 127, 247 ]; mockMessageEvent(this, msg); }; proto.queryAnalogMapping = function () { var msg = [ 240, 106, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 1, 2, 3, 4, 5, 6, 7, 247 ]; mockMessageEvent(this, msg); }; WebArduino.DEFAULT_SERVER = 'wss://ws.webduino.io:443'; WebArduino.SERVER_CHINA = 'wss://ws.webduino.com.cn'; function mockMessageEvent(board, message) { board._transport.emit(TransportEvent.MESSAGE, message); } scope.WebArduino = WebArduino; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var util = scope.util, Board = scope.Board, BoardEvent = scope.BoardEvent, proto; function Arduino(options) { if (typeof options === 'string') { options = { transport: 'serial', path: options }; } options = util.extend(getDefaultOptions(options), options); Board.call(this, options); } function getDefaultOptions(opts) { var def = { serial: { transport: 'serial', baudRate: 57600 }, bluetooth: { transport: 'bluetooth', uuid: '1101' } }; return def[opts.transport] || {}; } Arduino.prototype = proto = Object.create(Board.prototype, { constructor: { value: Arduino } }); proto.begin = function () { this.once(BoardEvent.FIRMWARE_NAME, this._initialVersionResultHandler); if (this._options.transport !== 'serial') { this.reportFirmware(); } }; scope.Arduino = Arduino; })); var chrome = chrome || {}; chrome._api = (function (window) { 'use strict'; var slice = Array.prototype.slice, undef = undefined, callbackHash = {}, listenerHash = {}, apiCalls = 0; function proxyRequest(api) { return function () { var params = slice.call(arguments), id = ++apiCalls + ''; if (typeof params[params.length - 1] === 'function') { callbackHash[id] = params.pop(); } invoke(id, api, params); }; } function proxyAddListener(api) { return function (listener) { var id = ++apiCalls + ''; if (typeof listener === 'function') { listenerHash[id] = listener; invoke(id, api, []); } }; } function proxyRemoveListener(api) { return function (listener) { Object.keys(listenerHash).some(function (id) { if (listenerHash[id] === listener) { delete listenerHash[id]; invoke(id, api, []); return true; } }); }; } function invoke(id, method, params) { delete chrome.runtime.lastError; window.postMessage({ jsonrpc: '2.0', id: id, method: method, params: params }, window.location.origin); } window.addEventListener('message', function (event) { var msg = event.data; if (msg.jsonrpc && !msg.method) { if (msg.exception) { if (callbackHash[msg.id]) { delete callbackHash[msg.id]; } throw new Error(msg.exception); } else { if (msg.error) { chrome.runtime.lastError = { message: msg.error }; } if (callbackHash[msg.id]) { callbackHash[msg.id].apply(undef, msg.result); delete callbackHash[msg.id]; } else if (listenerHash[msg.id]) { listenerHash[msg.id].apply(undef, msg.result); } } } }, false); return { proxyRequest: proxyRequest, proxyAddListener: proxyAddListener, proxyRemoveListener: proxyRemoveListener }; }(window)); chrome.runtime = chrome.runtime || {}; chrome.serial = chrome.serial || (function (_api) { 'use strict'; var slice = Array.prototype.slice, undef = undefined, proxyRequest = _api.proxyRequest, proxyAddListener = _api.proxyAddListener, proxyRemoveListener = _api.proxyRemoveListener, proxiedSend = proxyRequest('chrome.serial.send'); return { getDevices: proxyRequest('chrome.serial.getDevices'), connect: proxyRequest('chrome.serial.connect'), update: proxyRequest('chrome.serial.update'), disconnect: proxyRequest('chrome.serial.disconnect'), setPaused: proxyRequest('chrome.serial.setPaused'), getInfo: proxyRequest('chrome.serial.getInfo'), getConnections: proxyRequest('chrome.serial.getConnections'), send: function (connectionId, data, callback) { proxiedSend.apply(undef, [connectionId, slice.call(new Uint8Array(data)), callback]); }, flush: proxyRequest('chrome.serial.flush'), getControlSignals: proxyRequest('chrome.serial.getControlSignals'), setControlSignals: proxyRequest('chrome.serial.setControlSignals'), setBreak: proxyRequest('chrome.serial.setBreak'), clearBreak: proxyRequest('chrome.serial.clearBreak'), onReceive: { addListener: proxyAddListener('chrome.serial.onReceive.addListener'), removeListener: proxyRemoveListener('chrome.serial.onReceive.removeListener') }, onReceiveError: { addListener: proxyAddListener('chrome.serial.onReceiveError.addListener'), removeListener: proxyRemoveListener('chrome.serial.onReceiveError.removeListener') } }; }(chrome._api)); +(function (scope) { 'use strict'; var push = Array.prototype.push, serial = chrome.serial; var Transport = scope.Transport, TransportEvent = scope.TransportEvent, proto; function SerialTransport(options) { Transport.call(this, options); this._options = options; this._connectionId = null; this._sendTimer = null; this._buf = []; this._connHandler = onConnect.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); this._errorHandler = onError.bind(this); init(this); } function init(self) { var options = self._options; serial.onReceive.addListener(self._messageHandler); serial.onReceiveError.addListener(self._errorHandler); serial.connect(options.path, { bitrate: options.baudRate }, self._connHandler); } function onConnect(connectionInfo) { this._connectionId = connectionInfo.connectionId; this.emit(TransportEvent.OPEN); } function onMessage(message) { if (message.connectionId === this._connectionId) { this.emit(TransportEvent.MESSAGE, message.data); } } function onDisconnect(result) { serial.onReceive.removeListener(this._messageHandler); serial.onReceiveError.removeListener(this._errorHandler); delete this._connectionId; this.emit(TransportEvent.CLOSE); } function onError(info) { this.emit(TransportEvent.ERROR, new Error(JSON.stringify(info))); } function sendOut() { var payload = new Uint8Array(this._buf).buffer; this.isOpen && serial.send(this._connectionId, payload); clearBuf(this); } function clearBuf(self) { self._buf = []; clearImmediate(self._sendTimer); self._sendTimer = null; } SerialTransport.prototype = proto = Object.create(Transport.prototype, { constructor: { value: SerialTransport }, isOpen: { get: function () { return !!this._connectionId; } } }); proto.send = function (payload) { push.apply(this._buf, payload); if (!this._sendTimer) { this._sendTimer = setImmediate(this._sendOutHandler); } }; proto.close = function () { if (this._connectionId) { serial.disconnect(this._connectionId, this._disconnHandler); } }; scope.transport.serial = SerialTransport; }(webduino)); chrome.bluetooth = chrome.bluetooth || (function (_api) { 'use strict'; var proxyRequest = _api.proxyRequest; return { getAdapterState: proxyRequest('chrome.bluetooth.getAdapterState'), getDevice: proxyRequest('chrome.bluetooth.getDevice'), getDevices: proxyRequest('chrome.bluetooth.getDevices'), startDiscovery: proxyRequest('chrome.bluetooth.startDiscovery'), stopDiscovery: proxyRequest('chrome.bluetooth.stopDiscovery') }; }(chrome._api)); chrome.bluetoothSocket = chrome.bluetoothSocket || (function (_api) { 'use strict'; var slice = Array.prototype.slice, undef = undefined, proxyRequest = _api.proxyRequest, proxyAddListener = _api.proxyAddListener, proxyRemoveListener = _api.proxyRemoveListener, proxiedSend = proxyRequest('chrome.bluetoothSocket.send'); return { create: proxyRequest('chrome.bluetoothSocket.create'), connect: proxyRequest('chrome.bluetoothSocket.connect'), update: proxyRequest('chrome.bluetoothSocket.update'), disconnect: proxyRequest('chrome.bluetoothSocket.disconnect'), close: proxyRequest('chrome.bluetoothSocket.close'), setPaused: proxyRequest('chrome.bluetoothSocket.setPaused'), getInfo: proxyRequest('chrome.bluetoothSocket.getInfo'), getSockets: proxyRequest('chrome.bluetoothSocket.getSockets'), send: function (socketId, data, callback) { proxiedSend.apply(undef, [socketId, slice.call(new Uint8Array(data)), callback]); }, listenUsingRfcomm: proxyRequest('chrome.bluetoothSocket.listenUsingRfcomm'), listenUsingL2cap: proxyRequest('chrome.bluetoothSocket.listenUsingL2cap'), onAccept: { addListener: proxyAddListener('chrome.bluetoothSocket.onAccept.addListener'), removeListener: proxyRemoveListener('chrome.bluetoothSocket.onAccept.removeListener') }, onAcceptError: { addListener: proxyAddListener('chrome.bluetoothSocket.onAcceptError.addListener'), removeListener: proxyRemoveListener('chrome.bluetoothSocket.onAcceptError.removeListener') }, onReceive: { addListener: proxyAddListener('chrome.bluetoothSocket.onReceive.addListener'), removeListener: proxyRemoveListener('chrome.bluetoothSocket.onReceive.removeListener') }, onReceiveError: { addListener: proxyAddListener('chrome.bluetoothSocket.onReceiveError.addListener'), removeListener: proxyRemoveListener('chrome.bluetoothSocket.onReceiveError.removeListener') } }; }(chrome._api)); +(function (scope) { 'use strict'; var push = Array.prototype.push, bluetooth = chrome.bluetoothSocket; var Transport = scope.Transport, TransportEvent = scope.TransportEvent, retry = 0, proto; function BluetoothTransport(options) { Transport.call(this, options); this._options = options; this._socketId = null; this._sendTimer = null; this._buf = []; this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); this._errorHandler = onError.bind(this); init(this); } function init(self) { var options = self._options; getSocketId(options.address, function (err, socketId) { if (err || !socketId) { self.emit(TransportEvent.ERROR, new Error(err)); } else { bluetooth.onReceive.addListener(self._messageHandler); bluetooth.onReceiveError.addListener(self._errorHandler); bluetooth.connect(socketId, options.address, options.uuid, function () { if (chrome.runtime.lastError) { console.log(chrome.runtime.lastError.message); bluetooth.close(socketId, function () { bluetooth.onReceive.removeListener(self._messageHandler); bluetooth.onReceiveError.removeListener(self._errorHandler); if (++retry <= BluetoothTransport.MAX_RETRIES) { init(self); } else { self.emit(TransportEvent.ERROR, new Error('too many retries')); } }); } else { retry = 0; self._socketId = socketId; self.emit(TransportEvent.OPEN); } }); } }); } function getSocketId(address, callback) { var socketId; chrome.bluetooth.getAdapterState(function (state) { if (state.available) { chrome.bluetooth.getDevice(address, function (dev) { if (dev) { bluetooth.getSockets(function (scks) { scks.some(function (sck) { if (!sck.connected) { socketId = sck.socketId; return true; } }); if (typeof socketId === 'undefined') { bluetooth.create(function (createInfo) { callback(null, createInfo.socketId); }); } else { callback(null, socketId); } }); } else { callback('No such device "' + address + '"'); } }); } else { callback('Bluetooth adapter not available'); } }); } function onMessage(message) { if (message.socketId === this._socketId) { this.emit(TransportEvent.MESSAGE, message.data); } } function onDisconnect() { bluetooth.onReceive.removeListener(this._messageHandler); bluetooth.onReceiveError.removeListener(this._errorHandler); delete this._socketId; this.emit(TransportEvent.CLOSE); } function onError(info) { this.emit(TransportEvent.ERROR, new Error(JSON.stringify(info))); } function sendOut() { var payload = new Uint8Array(this._buf).buffer; this.isOpen && bluetooth.send(this._socketId, payload); clearBuf(this); } function clearBuf(self) { self._buf = []; clearImmediate(self._sendTimer); self._sendTimer = null; } BluetoothTransport.prototype = proto = Object.create(Transport.prototype, { constructor: { value: BluetoothTransport }, isOpen: { get: function () { return !!this._socketId; } } }); proto.send = function (payload) { push.apply(this._buf, payload); if (!this._sendTimer) { this._sendTimer = setImmediate(this._sendOutHandler); } }; proto.close = function () { if (this._socketId) { bluetooth.close(this._socketId, this._disconnHandler); } }; proto.flush = function () { if (this._buf && this._buf.length) { this._sendOutHandler(); } }; BluetoothTransport.MAX_RETRIES = 10; scope.transport.bluetooth = BluetoothTransport; }(webduino)); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var util = scope.util, Board = scope.Board; function Smart(options) { if (typeof options === 'string') { options = { url: options }; } options = util.extend(getDefaultOptions(), options); options.server = parseServer(options.server); Board.call(this, options); } function getDefaultOptions() { return { transport: 'websocket', server: Smart.DEFAULT_SERVER, login: 'admin', password: 'password', autoReconnect: false, multi: false, initialReset: true, handleDigitalPins: true }; } function parseServer(url) { if (url.indexOf('://') === -1) { url = (typeof location !== 'undefined' && location.protocol === 'https:' ? 'wss:' : 'ws:') + '//' + url; } url = util.parseURL(url); return url.protocol + '//' + url.host + '/'; } Smart.prototype = Object.create(Board.prototype, { constructor: { value: Smart } }); Smart.DEFAULT_SERVER = 'wss://ws.webduino.io:443'; Smart.SERVER_CHINA = 'wss://ws.webduino.com.cn'; scope.board.Smart = Smart; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var util = scope.util, Board = scope.Board, BoardEvent = scope.BoardEvent, proto; function Bit(options) { if (typeof options === 'string') { options = { url: options }; } options = util.extend(getDefaultOptions(), options); options.server = parseServer(options.server); Board.call(this, options); } function getDefaultOptions() { return { transport: 'websocket', server: Bit.DEFAULT_SERVER, login: 'admin', password: 'password', autoReconnect: false, multi: false, initialReset: true, handleDigitalPins: true }; } function parseServer(url) { if (url.indexOf('://') === -1) { url = (typeof location !== 'undefined' && location.protocol === 'https:' ? 'wss:' : 'ws:') + '//' + url; } url = util.parseURL(url); return url.protocol + '//' + url.host + '/'; } Bit.prototype = proto = Object.create(Board.prototype, { constructor: { value: Bit } }); Bit.DEFAULT_SERVER = 'wss://ws.webduino.io:443'; Bit.SERVER_CHINA = 'wss://ws.webduino.com.cn'; proto.startup = function () { this._isReady = true; this.emit(BoardEvent.READY, this); setTimeout(function() { if (this._options.transport === 'serial') { // wait for physical board ready to receive data from serialPort this.send([0xf0, 0x0e, 0x0c, 0xf7]); } }.bind(this), 500); }; scope.board.Bit = Bit; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var proto; var sendArray = []; var sending = false; var sendAck = ''; var sendCallback; var Module = scope.Module; var BoardEvent = scope.BoardEvent; var _callback; var _dataString; function toArray(str) { var data = []; for (var i = 0; i < str.length; i++) { data.push(str.charCodeAt(i)); } return data; } function DataTransfer(board) { Module.call(this); this._board = board; //board.send([0xF0, 0x04, 0x20, dataType /*init*/ , 0xF7]); board.on(BoardEvent.SYSEX_MESSAGE, function (event) { var data = event.message; sending = false; if (data[0] == 0x20) { switch (data[1] /*dataType*/ ) { case 0: //String var str = ''; for (var i = 2; i < data.length; i++) { str += String.fromCharCode(data[i]); } _dataString = str; _callback(0, str); break; } } }); startQueue(board); } DataTransfer.prototype = proto = Object.create(Module.prototype, { constructor: { value: DataTransfer } }); proto.sendString = function (msg, callback) { var cmdArray = [0xF0, 0x04, 0x20, 0x0]; cmdArray = cmdArray.concat(toArray(msg)); cmdArray.push(0xF7); this._board.send(cmdArray); if (callback !== undefined) { _callback = callback; } }; proto.onMessage = function (callback) { if (callback !== undefined) { _callback = callback; } }; proto.getDataString = function () { return _dataString; }; function startQueue(board) { setInterval(function () { if (sending || sendArray.length == 0) { return; } sending = true; var sendObj = sendArray.shift(); sendAck = sendObj.ack; if (sendAck > 0) { board.send(sendObj.obj); } else { sending = false; sendCallback(); } }, 0); } scope.module.DataTransfer = DataTransfer; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent; var self; var proto; var sendLen = 32; var lastSendIR = false; var debugFlag = false; function log(obj) { if (debugFlag) { console.log(obj); } } function IRRAW(board, pinMapping) { Module.call(this); this._board = board; this.pinSendIR = this.pinRecvIR = -1; self = this; if (typeof pinMapping === 'object') { if (pinMapping['send']) { this.pinSendIR = pinMapping['send']; } if (pinMapping['recv']) { this.pinRecvIR = pinMapping['recv']; } } onMessage(); } function onMessage() { self._board.on(BoardEvent.SYSEX_MESSAGE, function (event) { var m = event.message; //send IR data to Board if (m[0] == 0x04 && m[1] == 0x09 && m[2] == 0x0B) { log('send IR data to Board callback'); if (lastSendIR) { //store OK lastSendIR = false; log('send pin:' + self.pinSendIR); self._board.send([0xf0, 0x04, 0x09, 0x0C, self.pinSendIR, 0xF7]); } } //trigger IR send else if (m[0] == 0x04 && m[1] == 0x09 && m[2] == 0x0C) { log('trigger IR send callback...'); self.irSendCallback(); } //record IR data else if (m[0] == 0x04 && m[1] == 0x09 && m[2] == 0x0D) { log('record IR callback...'); var strInfo = ''; for (var i = 3; i < m.length; i++) { strInfo += String.fromCharCode(m[i]); } self.irData = strInfo.substring(4); self.irRecvCallback(self.irData); } else { log(event); } }); } function send(startPos, data) { var CMD = [0xf0, 0x04, 0x09, 0x0A]; var raw = []; raw = raw.concat(CMD); var n = '0000' + startPos.toString(16); n = n.substring(n.length - 4); for (var i = 0; i < 4; i++) { raw.push(n.charCodeAt(i)); } raw.push(0xf7); // send Data // CMD = [0xf0, 0x04, 0x09, 0x0B]; raw = raw.concat(CMD); for (i = 0; i < data.length; i++) { raw.push(data.charCodeAt(i)); } raw.push(0xf7); self._board.send(raw); } function sendIRCmd(cmd, len) { for (var i = 0; i < cmd.length; i = i + len) { var data = cmd.substring(i, i + len); send(i / 8, data); } lastSendIR = true; } IRRAW.prototype = proto = Object.create(Module.prototype, { constructor: { value: IRRAW } }); proto.recv = function (callback) { self.irRecvCallback = callback; if (self.pinRecvIR > 0) { self._board.send([0xF0, 0x04, 0x09, 0x0D, self.pinRecvIR, 0xF7]); log('wait recv...'); } }; proto.send = function (data, callback) { if (self.pinSendIR > 0) { sendIRCmd(data, sendLen); self.irSendCallback = callback; } }; proto.debug = function (val) { if (typeof val == 'boolean') { self.isDebug = val; } }; proto.sendPin = function (pin) { this.pinSendIR = pin; }; proto.recvPin = function (pin) { this.pinRecvIR = pin; }; scope.module.IRRAW = IRRAW; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var self; var proto; var sendArray = []; var sending = false; var sendAck = ''; var sendCallback; var Module = scope.Module; var BoardEvent = scope.BoardEvent; var sendAndAckCount = 0; var waitAckAndSend = []; var _play; function DFPlayer(board, RX, TX) { Module.call(this); this._board = board; this._rx = RX; this._tx = TX; self = this; board.on(BoardEvent.SYSEX_MESSAGE, function () { sendAndAckCount--; sending = false; if (waitAckAndSend.length > 0) { var cmd = waitAckAndSend.shift(); self._board.send(cmd); } }); startQueue(board); } DFPlayer.prototype = proto = Object.create(Module.prototype, { constructor: { value: DFPlayer }, play: { get: function () { return _play; }, set: function (val) { _play = val; } } }); proto.init = function () { var cmd = [0xF0, 0x04, 0x19, 0x0 /*init*/ , this._rx, this._tx, 0xF7]; sendAndAckCount++; this._board.send(cmd); }; proto.play = function (num) { var cmd = [0xF0, 0x04, 0x19, 0x01, num, 0xF7]; sendAndAckCount++; waitAckAndSend.push(cmd); }; proto.start = function () { sendAndAckCount++; waitAckAndSend.push([0xF0, 0x04, 0x19, 0x02 /*Start*/ , 0xF7]); }; proto.stop = function () { sendAndAckCount++; waitAckAndSend.push([0xF0, 0x04, 0x19, 0x03 /*Stop*/ , 0xF7]); }; proto.pause = function () { sendAndAckCount++; waitAckAndSend.push([0xF0, 0x04, 0x19, 0x04 /*Pause*/ , 0xF7]); }; proto.volume = function (volume) { sendAndAckCount++; waitAckAndSend.push([0xF0, 0x04, 0x19, 0x05, volume, 0xF7]); }; proto.previous = function () { sendAndAckCount++; waitAckAndSend.push([0xF0, 0x04, 0x19, 0x06 /*Previous*/ , 0xF7]); }; proto.next = function () { sendAndAckCount++; waitAckAndSend.push([0xF0, 0x04, 0x19, 0x07 /*Next*/ , 0xF7]); }; proto.loop = function (num) { sendAndAckCount++; waitAckAndSend.push([0xF0, 0x04, 0x19, 0x08, num, 0xF7]); }; function startQueue(board) { setInterval(function () { if (sendAndAckCount == waitAckAndSend.length && waitAckAndSend.length > 0) { var cmd = waitAckAndSend.shift(); board.send(cmd); } if (sending || sendArray.length == 0) { return; } sending = true; var sendObj = sendArray.shift(); sendAck = sendObj.ack; if (sendAck > 0) { board.send(sendObj.obj); } else { sending = false; sendCallback(); } }, 0); } scope.module.DFPlayer = DFPlayer; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var proto; var sendArray = []; var sending = false; var sendAck = ''; var sendCallback; var Module = scope.Module; var BoardEvent = scope.BoardEvent; var _backlight; function LCD1602(board) { Module.call(this); this._board = board; board.send([0xF0, 0x04, 0x18, 0x0 /*init*/ , 0xF7]); board.on(BoardEvent.SYSEX_MESSAGE, function () { sending = false; }); startQueue(board); } LCD1602.prototype = proto = Object.create(Module.prototype, { constructor: { value: LCD1602 }, backlight: { get: function () { return _backlight; }, set: function (val) { _backlight = val; } } }); proto.print = function (txt) { var cmd = [0xF0, 0x04, 0x18, 0x02]; cmd = cmd.concat(toASCII(txt)); cmd.push(0xF7); this._board.send(cmd); }; proto.cursor = function (col, row) { this._board.send([0xF0, 0x04, 0x18, 0x01, col, row, 0xF7]); }; proto.clear = function () { this._board.send([0xF0, 0x04, 0x18, 0x03, 0xF7]); }; function toASCII(str) { var data = []; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i).toString(16); if (charCode.length == 1) { charCode = '0' + charCode; } var highChar = charCode.charAt(0); var lowChar = charCode.charAt(1); data.push(highChar.charCodeAt(0)); data.push(lowChar.charCodeAt(0)); } return data; } function startQueue(board) { setInterval(function () { if (sending || sendArray.length == 0) { return; } sending = true; var sendObj = sendArray.shift(); sendAck = sendObj.ack; if (sendAck > 0) { board.send(sendObj.obj); } else { sending = false; sendCallback(); } }, 0); } scope.module.LCD1602 = LCD1602; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Pin = scope.Pin, Module = scope.Module, BoardEvent = scope.BoardEvent, proto; /** * The Led class. * * @namespace webduino.module * @class Led * @constructor * @param {webduino.Board} board The board the LED is attached to. * @param {webduino.Pin} pin The pin the LED is connected to. * @param {Number} [driveMode] Drive mode the LED is operating at, either Led.SOURCE_DRIVE or Led.SYNC_DRIVE. * @extends webduino.Module */ function Led(board, pin, driveMode) { Module.call(this); this._board = board; this._pin = pin; this._driveMode = driveMode || Led.SOURCE_DRIVE; this._supportsPWM = undefined; this._blinkTimer = null; this._board.on(BoardEvent.BEFOREDISCONNECT, this._clearBlinkTimer.bind(this)); this._board.on(BoardEvent.ERROR, this._clearBlinkTimer.bind(this)); if (this._driveMode === Led.SOURCE_DRIVE) { this._onValue = 1; this._offValue = 0; } else if (this._driveMode === Led.SYNC_DRIVE) { this._onValue = 0; this._offValue = 1; } else { throw new Error('driveMode should be Led.SOURCE_DRIVE or Led.SYNC_DRIVE'); } if (pin.capabilities[Pin.PWM]) { board.setDigitalPinMode(pin.number, Pin.PWM); this._supportsPWM = true; } else { board.setDigitalPinMode(pin.number, Pin.DOUT); this._supportsPWM = false; } } function checkPinState(self, pin, state, callback) { self._board.queryPinState(pin, function (pin) { if (pin.state === state) { callback.call(self); } }); } Led.prototype = proto = Object.create(Module.prototype, { constructor: { value: Led }, /** * Intensity of the LED. * * @attribute intensity * @type {Number} */ intensity: { get: function () { return this._pin.value; }, set: function (val) { if (!this._supportsPWM) { if (val < 0.5) { val = 0; } else { val = 1; } } if (this._driveMode === Led.SOURCE_DRIVE) { this._pin.value = val; } else if (this._driveMode === Led.SYNC_DRIVE) { this._pin.value = 1 - val; } } } }); /** * Light up the LED. * * @method on * @param {Function} [callback] LED state changed callback. */ proto.on = function (callback) { this._clearBlinkTimer(); this._pin.value = this._onValue; if (typeof callback === 'function') { checkPinState(this, this._pin, this._pin.value, callback); } }; /** * Dim the LED. * * @method off * @param {Function} [callback] LED state changed callback. */ proto.off = function (callback) { this._clearBlinkTimer(); this._pin.value = this._offValue; if (typeof callback === 'function') { checkPinState(this, this._pin, this._pin.value, callback); } }; /** * Toggle LED state between on/off. * * @method toggle * @param {Function} [callback] State changed callback. */ proto.toggle = function (callback) { if (this._blinkTimer) { this.off(); } else { this._pin.value = 1 - this._pin.value; } if (typeof callback === 'function') { checkPinState(this, this._pin, this._pin.value, callback); } }; /** * Blink the LED. * * @method blink * @param {Number} [interval=1000] Led blinking interval. * @param {Function} [callback] Led state changed callback. */ proto.blink = function (interval, callback) { if (arguments.length === 1 && typeof arguments[0] === 'function') { callback = arguments[0]; } interval = parseInt(interval); interval = isNaN(interval) || interval <= 0 ? 1000 : interval; this._clearBlinkTimer(); this._blinkTimer = this._blink(interval, callback); }; proto._blink = function (interval, callback) { var self = this; return setTimeout(function () { self._pin.value = 1 - self._pin.value; if (typeof callback === 'function') { checkPinState(self, self._pin, self._pin.value, callback); } self._blinkTimer = self._blink(interval, callback); }, interval); }; proto._clearBlinkTimer = function () { if (this._blinkTimer) { clearTimeout(this._blinkTimer); this._blinkTimer = null; } }; /** * Indicates the source LED drive mode. * * @property SOURCE_DRIVE * @type Number * @static * @final */ Led.SOURCE_DRIVE = 0; /** * Indicates the synchronous LED drive mode. * * @property SYNC_DRIVE * @type Number * @static * @final */ Led.SYNC_DRIVE = 1; scope.module.Led = Led; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Led = scope.module.Led, Module = scope.Module, proto; /** * The RGBLed Class. * * @namespace webduino.module * @class RGBLed * @constructor * @param {webduino.Board} board The board the RGB LED is attached to. * @param {webduino.Pin} redLedPin The pin the red LED is connected to. * @param {webduino.Pin} greenLedPin The pin the green LED is connected to. * @param {webduino.Pin} blueLedPin The pin the blue LED is connected to. * @param {Number} [driveMode] Drive mode the RGB LED is operating at, either RGBLed.COMMON_ANODE or RGBLed.COMMON_CATHODE. * @extends webduino.Module */ function RGBLed(board, redLedPin, greenLedPin, blueLedPin, driveMode) { Module.call(this); if (driveMode === undefined) { driveMode = RGBLed.COMMON_ANODE; } this._board = board; this._redLed = new Led(board, redLedPin, driveMode); this._greenLed = new Led(board, greenLedPin, driveMode); this._blueLed = new Led(board, blueLedPin, driveMode); this.setColor(0, 0, 0); } function hexToR(h) { return parseInt(h.substring(0, 2), 16); } function hexToG(h) { return parseInt(h.substring(2, 4), 16); } function hexToB(h) { return parseInt(h.substring(4, 6), 16); } function cutHex(h) { return (h.charAt(0) == '#') ? h.substring(1, 7) : h; } RGBLed.prototype = proto = Object.create(Module.prototype, { constructor: { value: RGBLed } }); /** * Light up and mix colors with the LEDs. * * @method setColor * @param {Number} red The brightness of the red LED. * @param {Number} green The brightness of the green LED. * @param {Number} blue The brightness of the blue LED. * @param {Function} [callback] Function to call when the color is set. */ proto.setColor = function (red, green, blue, callback) { if (typeof green === 'undefined' || typeof green === 'function') { var color = cutHex(red); callback = green; red = hexToR(color); green = hexToG(color); blue = hexToB(color); } red = red / 255; green = green / 255; blue = blue / 255; this._redLed.intensity = red; this._greenLed.intensity = green; this._blueLed.intensity = blue; if (typeof callback === 'function') { var self = this, redPin = this._redLed._pin, greenPin = this._greenLed._pin, bluePin = this._blueLed._pin; this._board.queryPinState([redPin, greenPin, bluePin], function (pins) { if (pins[0].state === redPin.value && pins[1].state === greenPin.value && pins[2].state === bluePin.value) { callback.call(self); } }); } }; /** * Indicates the common anode drive mode. * * @property COMMON_ANODE * @type {Number} * @static * @final */ RGBLed.COMMON_ANODE = Led.SYNC_DRIVE; /** * Indicates the common cathode drive mode. * * @property COMMON_CATHODE * @type {Number} * @static * @final */ RGBLed.COMMON_CATHODE = Led.SOURCE_DRIVE; scope.module.RGBLed = RGBLed; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var PinEvent = scope.PinEvent, Pin = scope.Pin, Module = scope.Module; var ButtonEvent = { /** * Fires when a button is pressed. * * @event ButtonEvent.PRESS */ PRESS: 'pressed', /** * Fires when a button is released. * * @event ButtonEvent.RELEASE */ RELEASE: 'released', /** * Fires when a button is long-pressed. * * @event ButtonEvent.LONG_PRESS */ LONG_PRESS: 'longPress', /** * Fires when a button is sustained-pressed. * * @event ButtonEvent.SUSTAINED_PRESS */ SUSTAINED_PRESS: 'sustainedPress' }; /** * The Button Class. * * @namespace webduino.module * @class Button * @constructor * @param {webduino.Board} board The board the button is attached to. * @param {webduino.pin} pin The pin the button is connected to. * @param {Number} [buttonMode] Type of resistor the button is connected to, either Button.PULL_DOWN or Button.PULL_UP. * @param {Number} [sustainedPressInterval] A period of time when the button is pressed and hold for that long, it would be considered a "sustained press." Measured in ms. * @extends webduino.Module */ function Button(board, pin, buttonMode, sustainedPressInterval) { Module.call(this); this._board = board; this._pin = pin; this._repeatCount = 0; this._timer = null; this._timeout = null; this._buttonMode = buttonMode || Button.PULL_DOWN; this._sustainedPressInterval = sustainedPressInterval || 1000; this._debounceInterval = 20; this._pressHandler = onPress.bind(this); this._releaseHandler = onRelease.bind(this); this._sustainedPressHandler = onSustainedPress.bind(this); board.setDigitalPinMode(pin.number, Pin.DIN); if (this._buttonMode === Button.INTERNAL_PULL_UP) { board.enablePullUp(pin.number); this._pin.value = Pin.HIGH; } else if (this._buttonMode === Button.PULL_UP) { this._pin.value = Pin.HIGH; } this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); } function onPinChange(pin) { var btnVal = pin.value; var stateHandler; if (this._buttonMode === Button.PULL_DOWN) { if (btnVal === 1) { stateHandler = this._pressHandler; } else { stateHandler = this._releaseHandler; } } else if (this._buttonMode === Button.PULL_UP || this._buttonMode === Button.INTERNAL_PULL_UP) { if (btnVal === 1) { stateHandler = this._releaseHandler; } else { stateHandler = this._pressHandler; } } if (this._timeout) { clearTimeout(this._timeout); } this._timeout = setTimeout(stateHandler, this._debounceInterval); } function onPress() { this.emit(ButtonEvent.PRESS); if (this._timer) { clearInterval(this._timer); delete this._timer; } this._timer = setInterval(this._sustainedPressHandler, this._sustainedPressInterval); } function onRelease() { this.emit(ButtonEvent.RELEASE); if (this._timer) { clearInterval(this._timer); delete this._timer; } this._repeatCount = 0; } function onSustainedPress() { if (this._repeatCount > 0) { this.emit(ButtonEvent.SUSTAINED_PRESS); } else { this.emit(ButtonEvent.LONG_PRESS); } this._repeatCount++; } Button.prototype = Object.create(Module.prototype, { constructor: { value: Button }, /** * Return the button mode. * * @attribute buttonMode * @type {Number} buttonMode * @readOnly */ buttonMode: { get: function () { return this._buttonMode; } }, /** * Return the sustained-press interval. * * @attribute sustainedPressInterval * @type {Number} */ sustainedPressInterval: { get: function () { return this._sustainedPressInterval; }, set: function (intervalTime) { this._sustainedPressInterval = intervalTime; } } }); /** * Indicates the pull-down resistor type. * * @property PULL_DOWN * @type {Number} * @static * @final */ Button.PULL_DOWN = 0; /** * Indicates the pull-up resistor type. * * @property PULL_UP * @type {Number} * @static * @final */ Button.PULL_UP = 1; /** * Indicates the internal-pull-up resistor type. * * @property INTERNAL_PULL_UP * @type {Number} * @static * @final */ Button.INTERNAL_PULL_UP = 2; scope.module.ButtonEvent = ButtonEvent; scope.module.Button = Button; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var ULTRASONIC_MESSAGE = 0x01, MIN_PING_INTERVAL = 20, MIN_RESPONSE_TIME = 30, RETRY_INTERVAL = 5000; var UltrasonicEvent = { /** * Fires when receiving a ping response. * * @event UltrasonicEvent.PING */ PING: 'ping', /** * Fires when receiving a ping-error response. * * @event UltrasonicEvent.PING_ERROR */ PING_ERROR: 'pingError' }; /** * The Ultrasonic class. * * @namespace webduino.module * @class Ultrasonic * @constructor * @param {webduino.Board} board The board the ultrasonic sensor is attached to. * @param {webduino.Pin} trigger The trigger pin the sensor is connected to. * @param {webduino.Pin} echo The echo pin the sensor is connected to. * @extends webduino.Module */ function Ultrasonic(board, trigger, echo) { Module.call(this); this._type = 'HC-SR04'; this._board = board; this._trigger = trigger; this._echo = echo; this._distance = null; this._lastRecv = null; this._pingTimer = null; this._pingCallback = function () {}; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopPing.bind(this)); this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.ERROR, this.stopPing.bind(this)); } function onMessage(event) { var message = event.message; if (message[0] !== ULTRASONIC_MESSAGE) { return; } else { processUltrasonicData(this, message); } } function processUltrasonicData(self, data) { var str = '', i = 3, d1, d2; if (data[1] === self._trigger.number && data[2] === self._echo.number) { while (i < data.length) { d1 = data[i]; d2 = data[i + 1]; str += (d1 - 48); d2 && (str += (d2 - 48)); i += 2; } self._lastRecv = Date.now(); self.emit(UltrasonicEvent.PING, parseInt(str)); } } Ultrasonic.prototype = proto = Object.create(Module.prototype, { constructor: { value: Ultrasonic }, /** * Distance returned from the previous transmission. * * @attribute distance * @type {Number} * @readOnly */ distance: { get: function () { return this._distance; } } }); /** * Transmit an ultrasonic to sense the distance at a (optional) given interval. * * @method ping * @param {Function} [callback] Callback when a response is returned. * @param {Number} [interval] Interval between each transmission. If omitted the ultrasonic will be transmitted once. * @return {Promise} A promise when the ping response is returned. Will not return anything if a callback function is given. */ proto.ping = function (callback, interval) { var self = this, timer; self.stopPing(); if (typeof callback === 'function') { self._pingCallback = function (distance) { self._distance = distance; callback(distance); }; self._board.on(BoardEvent.SYSEX_MESSAGE, self._messageHandler); self.on(UltrasonicEvent.PING, self._pingCallback); timer = function () { self._board.sendSysex(ULTRASONIC_MESSAGE, [self._trigger.number, self._echo.number]); if (interval) { interval = Math.max(interval, MIN_PING_INTERVAL); if (self._lastRecv === null || Date.now() - self._lastRecv < 5 * interval) { self._pingTimer = setTimeout(timer, interval); } else { self.stopPing(); setTimeout(function () { self.ping(callback, interval); }, RETRY_INTERVAL); } } }; timer(); } else { return new Promise(function (resolve) { self.ping(function (cm) { setTimeout(function () { resolve(cm); }, MIN_RESPONSE_TIME); }); }); } }; /** * Stop transmitting any ultrasonic. * * @method stopPing */ proto.stopPing = function () { this.removeListener(UltrasonicEvent.PING, this._pingCallback); this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this._lastRecv = null; if (this._pingTimer) { clearTimeout(this._pingTimer); delete this._pingTimer; } }; scope.module.UltrasonicEvent = UltrasonicEvent; scope.module.Ultrasonic = Ultrasonic; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Pin = scope.Pin, Module = scope.Module; function Servo(board, pin, minAngle, maxAngle) { Module.call(this); this._type = 'SG90'; this._board = board; this._pin = pin; this._angle = undefined; this._minAngle = minAngle || 0; this._maxAngle = maxAngle || 180; board.sendServoAttach(pin.number); board.setDigitalPinMode(pin.number, Pin.SERVO); } Servo.prototype = Object.create(Module.prototype, { constructor: { value: Servo }, angle: { get: function () { if (this._pin._type === Pin.SERVO) { return this._angle; } }, set: function (val) { if (this._pin._type === Pin.SERVO) { this._angle = val; this._pin.value = Math.max(0, Math.min(1, (this._angle - this._minAngle) / (this._maxAngle - this._minAngle) * Servo.COEF_TO_0_180)); } } } }); Servo.COEF_TO_0_180 = 180 / 255; scope.module.Servo = Servo; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var PinEvent = scope.PinEvent, Pin = scope.Pin, Module = scope.Module; var TiltEvent = { HIGH: 'high', LOW: 'low' }; function Tilt(board, pin) { Module.call(this); this._board = board; this._pin = pin; board.setDigitalPinMode(pin.number, Pin.DIN); this._pin.value = Pin.HIGH; this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); } function onPinChange(pin) { if (pin.value === Pin.HIGH) { this.emit(TiltEvent.HIGH); } else { this.emit(TiltEvent.LOW); } } Tilt.prototype = Object.create(Module.prototype, { constructor: { value: Tilt } }); scope.module.TiltEvent = TiltEvent; scope.module.Tilt = Tilt; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var PinEvent = scope.PinEvent, Pin = scope.Pin, Module = scope.Module; var PirEvent = { DETECTED: 'detected', ENDED: 'ended' }; function Pir(board, pin) { Module.call(this); this._board = board; this._pin = pin; board.setDigitalPinMode(pin.number, Pin.DIN); this._pin.value = Pin.HIGH; this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); } function onPinChange(pin) { if (pin.value === Pin.HIGH) { this.emit(PirEvent.DETECTED); } else { this.emit(PirEvent.ENDED); } } Pir.prototype = Object.create(Module.prototype, { constructor: { value: Pir } }); scope.module.PirEvent = PirEvent; scope.module.Pir = Pir; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var PinEvent = scope.PinEvent, Pin = scope.Pin, Module = scope.Module; var ShockEvent = { HIGH: 'high', LOW: 'low' }; function Shock(board, pin) { Module.call(this); this._board = board; this._pin = pin; board.setDigitalPinMode(pin.number, Pin.DIN); this._pin.value = Pin.HIGH; this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); } function onPinChange(pin) { if (pin.value === Pin.HIGH) { this.emit(ShockEvent.HIGH); } else { this.emit(ShockEvent.LOW); } } Shock.prototype = Object.create(Module.prototype, { constructor: { value: Shock } }); scope.module.ShockEvent = ShockEvent; scope.module.Shock = Shock; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var PinEvent = scope.PinEvent, Pin = scope.Pin, Module = scope.Module; var SoundEvent = { DETECTED: 'detected', ENDED: 'ended' }; function Sound(board, pin) { Module.call(this); this._type = 'FC_04'; this._board = board; this._pin = pin; board.setDigitalPinMode(pin.number, Pin.DIN); this._pin.value = Pin.HIGH; this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); } function onPinChange(pin) { if (pin.value === Pin.LOW) { this.emit(SoundEvent.DETECTED); } else { this.emit(SoundEvent.ENDED); } } Sound.prototype = Object.create(Module.prototype, { constructor: { value: Sound } }); scope.module.SoundEvent = SoundEvent; scope.module.Sound = Sound; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Pin = scope.Pin, Module = scope.Module, proto; function Relay(board, pin) { Module.call(this); this._type = 'KY-019'; this._board = board; this._pin = pin; this._onValue = 1; this._offValue = 0; board.setDigitalPinMode(pin.number, Pin.DOUT); this.off(); } function checkPinState(self, pin, state, callback) { self._board.queryPinState(pin, function (pin) { if (pin.state === state) { callback.call(self); } }); } Relay.prototype = proto = Object.create(Module.prototype, { constructor: { value: Relay } }); proto.on = function (callback) { this._pin.value = this._onValue; if (typeof callback === 'function') { checkPinState(this, this._pin, this._pin.value, callback); } }; proto.off = function (callback) { this._pin.value = this._offValue; if (typeof callback === 'function') { checkPinState(this, this._pin, this._pin.value, callback); } }; proto.toggle = function (callback) { this._pin.value = 1 - this._pin.value; if (typeof callback === 'function') { checkPinState(this, this._pin, this._pin.value, callback); } }; scope.module.Relay = Relay; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var DHT_MESSAGE = [0x04, 0x04], MIN_READ_INTERVAL = 1000, MIN_RESPONSE_TIME = 30, RETRY_INTERVAL = 6000; var DhtEvent = { /** * Fires when reading value. * * @event DhtEvent.READ */ READ: 'read', /** * Fires when error occured while reading value. * * @event DhtEvent.READ_ERROR */ READ_ERROR: 'readError' }; /** * The Dht Class. * * DHT is sensor for measuring temperature and humidity. * * @namespace webduino.module * @class Dht * @constructor * @param {webduino.Board} board The board that the DHT is attached to. * @param {Integer} pin The pin that the DHT is connected to. * @extends webduino.Module */ function Dht(board, pin) { Module.call(this); this._type = 'DHT11'; this._board = board; this._pin = pin; this._humidity = null; this._temperature = null; this._lastRecv = null; this._readTimer = null; this._readCallback = function () {}; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopRead.bind(this)); this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.ERROR, this.stopRead.bind(this)); } function onMessage(event) { var message = event.message; if (message[0] !== DHT_MESSAGE[0] || message[1] !== DHT_MESSAGE[1]) { return; } else { processDhtData(this, message); } } function processDhtData(self, data) { var str = '', i = 3, MAX = 4, dd = [], d1, d2; if (data[2] === self._pin.number) { while (i < data.length) { d1 = data[i]; d2 = data[i + 1]; str += (d1 - 48); d2 && (str += (d2 - 48)); i += 2; if ((i - 3) % MAX === 0) { dd.push(parseInt(str) / 100); str = ''; } } self._lastRecv = Date.now(); self.emit(DhtEvent.READ, dd[0], dd[1]); } } Dht.prototype = proto = Object.create(Module.prototype, { constructor: { value: Dht }, /** * Return the humidity. * * @attribute humidity * @type {Number} humidity * @readOnly */ humidity: { get: function () { return this._humidity; } }, /** * Return the temperature. * * @attribute temperature * @type {Number} temperature * @readOnly */ temperature: { get: function () { return this._temperature; } } }); /** * Start reading data from sensor. * * @method read * @param {Function} [callback] reading callback. * @param {Integer} interval reading interval. * @param {Object} callback.data returned data from sensor, * humidity and temperature will be passed into callback function as parameters. * * callback() * * will be transformed to * * callback({humidity: humidity, temperature: temperature}) * * automatically. */ proto.read = function (callback, interval) { var self = this, timer; self.stopRead(); if (typeof callback === 'function') { self._readCallback = function (humidity, temperature) { self._humidity = humidity; self._temperature = temperature; callback({ humidity: humidity, temperature: temperature }); }; self._board.on(BoardEvent.SYSEX_MESSAGE, self._messageHandler); self.on(DhtEvent.READ, self._readCallback); timer = function () { self._board.sendSysex(DHT_MESSAGE[0], [DHT_MESSAGE[1], self._pin.number]); if (interval) { interval = Math.max(interval, MIN_READ_INTERVAL); if (self._lastRecv === null || Date.now() - self._lastRecv < 5 * interval) { self._readTimer = setTimeout(timer, interval); } else { self.stopRead(); setTimeout(function () { self.read(callback, interval); }, RETRY_INTERVAL); } } }; timer(); } else { return new Promise(function (resolve) { self.read(function (data) { self._humidity = data.humidity; self._temperature = data.temperature; setTimeout(function () { resolve(data); }, MIN_RESPONSE_TIME); }); }); } }; /** * Stop reading value from sensor. * * @method stopRead */ proto.stopRead = function () { this.removeListener(DhtEvent.READ, this._readCallback); this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this._lastRecv = null; if (this._readTimer) { clearTimeout(this._readTimer); delete this._readTimer; } }; scope.module.DhtEvent = DhtEvent; scope.module.Dht = Dht; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var push = Array.prototype.push; var util = scope.util, Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var BUZZER_MESSAGE = [0x04, 0x07], TONE_MIN_LENGTH = 100; var BUZZER_STATE = { PLAYING: 'playing', STOPPED: 'stopped', PAUSED: 'paused' }; var FREQUENCY = { REST: 0, B0: 31, C1: 33, CS1: 35, D1: 37, DS1: 39, E1: 41, F1: 44, FS1: 46, G1: 49, GS1: 52, A1: 55, AS1: 58, B1: 62, C2: 65, CS2: 69, D2: 73, DS2: 78, E2: 82, F2: 87, FS2: 93, G2: 98, GS2: 104, A2: 110, AS2: 117, B2: 123, C3: 131, CS3: 139, D3: 147, DS3: 156, E3: 165, F3: 175, FS3: 185, G3: 196, GS3: 208, A3: 220, AS3: 233, B3: 247, C4: 262, CS4: 277, D4: 294, DS4: 311, E4: 330, F4: 349, FS4: 370, G4: 392, GS4: 415, A4: 440, AS4: 466, B4: 494, C5: 523, CS5: 554, D5: 587, DS5: 622, E5: 659, F5: 698, FS5: 740, G5: 784, GS5: 831, A5: 880, AS5: 932, B5: 988, C6: 1047, CS6: 1109, D6: 1175, DS6: 1245, E6: 1319, F6: 1397, FS6: 1480, G6: 1568, GS6: 1661, A6: 1760, AS6: 1865, B6: 1976, C7: 2093, CS7: 2217, D7: 2349, DS7: 2489, E7: 2637, F7: 2794, FS7: 2960, G7: 3136, GS7: 3322, A7: 3520, AS7: 3729, B7: 3951, C8: 4186, CS8: 4435, D8: 4699, DS8: 4978 }; /** * The Buzzer Class. * * @namespace webduino.module * @class Buzzer * @constructor * @param {webduino.Board} board The board that the buzzer is attached to. * @param {Integer} pin The pin that the buzzer is connected to. * @extends webduino.Module */ function Buzzer(board, pin) { Module.call(this); this._board = board; this._pin = pin; this._timer = null; this._sequence = null; this._state = BUZZER_STATE.STOPPED; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stop.bind(this)); this._board.on(BoardEvent.ERROR, this.stop.bind(this)); } function getDuration(duration) { duration = isNaN(duration = parseInt(duration)) ? TONE_MIN_LENGTH : duration; return Math.max(duration, TONE_MIN_LENGTH); } function padDurations(durations, len) { var durLen = durations.length, dur = durLen ? durations[durLen - 1] : TONE_MIN_LENGTH; if (durLen < len) { push.apply(durations, new Array(len - durLen)); for (var i = durLen; i < durations.length; i++) { durations[i] = dur; } } return durations; } function playNext(self) { var seq = self._sequence, note; if (seq && seq.length > 0) { note = seq.pop(); self.tone(note.frequency, note.duration); self._timer = setTimeout(function () { playNext(self); }, note.duration + Buzzer.TONE_DELAY); } else { self.stop(); } } Buzzer.prototype = proto = Object.create(Module.prototype, { constructor: { value: Buzzer } }); /** * Set Buzzer tone. * * @method tone * @param {Integer} freq Frequency of tone. * @param {Integer} duration Duration of tone. */ proto.tone = function (freq, duration) { var freqData = []; if (isNaN(freq = parseInt(freq)) || freq <= 0 || freq > 9999) { return; } freq = ('0000' + freq).substr(-4, 4); freqData[0] = parseInt('0x' + freq[0] + freq[1]); freqData[1] = parseInt('0x' + freq[2] + freq[3]); duration = Math.round(getDuration(duration) / TONE_MIN_LENGTH); this._board.sendSysex(BUZZER_MESSAGE[0], [BUZZER_MESSAGE[1], this._pin.number] .concat(freqData).concat(duration)); }; /** * Play specified note and tempo. * * @method play * @param {Array} notes Array of notes. * @param {Array} tempos Array of tempos. * @example * buzzer.play(["C6","D6","E6","F6","G6","A6","B6"], ["8","8","8","8","8","8","8"]); */ proto.play = function (notes, tempos) { if (typeof notes !== 'undefined') { var len = notes.length, durations = padDurations( (util.isArray(tempos) ? tempos : []).map(function (t) { return getDuration(1000 / t); }), len ); this.stop(); this._sequence = []; for (var i = len - 1; i >= 0; i--) { this._sequence.push({ frequency: FREQUENCY[notes[i].toUpperCase()], duration: durations[i] }); } } else { if (this._state === BUZZER_STATE.PLAYING) { return; } } this._state = BUZZER_STATE.PLAYING; playNext(this); }; /** * Pause the playback. * * @method pause */ proto.pause = function () { if (this._state !== BUZZER_STATE.PLAYING) { return; } if (this._timer) { clearTimeout(this._timer); delete this._timer; } this._state = BUZZER_STATE.PAUSED; }; /** * Stop the plaback. * * @method stop */ proto.stop = function () { if (this._timer) { clearTimeout(this._timer); delete this._timer; } delete this._sequence; this._state = BUZZER_STATE.STOPPED; }; /** * Indicates the frequency of tone. * * @property FREQUENCY * @type {Number} * @static * @final */ Buzzer.FREQUENCY = FREQUENCY; /** * Indicates the delay of tone. * * @property TONE_DELAY * @type {Number} * @static * @final */ Buzzer.TONE_DELAY = 60; scope.module.Buzzer = Buzzer; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; /** * The Max7219 Class. * * MAX7219 is compact, serial input/output * common-cathode display drivers that interface * microprocessors (ยตPs) to 7-segment numeric LED displays * of up to 8 digits, bar-graph displays, or 64 individual LEDs. * * @namespace webduino.module * @class Max7219 * @constructor * @param {webduino.Board} board The board that the Max7219 is attached to. * @param {Integer} din Pin number of DIn (Data In). * @param {Integer} cs Pin number of LOAD/CS. * @param {Integer} clk Pin number of CLK. * @extends webduino.Module */ function Max7219(board, din, cs, clk) { Module.call(this); this._board = board; this._din = din; this._cs = cs; this._clk = clk; this._intensity = 0; this._data = 'ffffffffffffffff'; this._board.on(BoardEvent.BEFOREDISCONNECT, this.animateStop.bind(this)); this._board.on(BoardEvent.ERROR, this.animateStop.bind(this)); this._board.send([0xf0, 4, 8, 0, din.number, cs.number, clk.number, 0xf7]); } Max7219.prototype = proto = Object.create(Module.prototype, { constructor: { value: Max7219 }, /** * The intensity indicating brightness of Max7219. * * @attribute intensity * @type {Integer} Value of brightness (0~15). */ intensity: { get: function () { return this._intensity; }, set: function (val) { if (val >= 0 && val <= 15) { this._board.send([0xf0, 4, 8, 3, val, 0xf7]); this._intensity = val; } } } }); /** * Show pattern LED matrix. * * @method on * @param {String} data Pattern to display. * @example * matrix.on("0000000000000000"); */ proto.on = function (data) { if (data) { this._data = data; } else { data = this._data; } if (!data) { return false; } var sendData = [0xf0, 4, 8, 1]; var i = 0; var len = data.length; for (; i < len; i++) { sendData.push(data.charCodeAt(i)); } sendData.push(0xf7); this._board.send(sendData); }; /** * Clear pattern on LED matrix. * * @method off */ proto.off = function () { this._board.send([0xf0, 4, 8, 2, 0xf7]); }; /** * Display animated pattern. * * @method animate * @param {Array} data Array of patterns. * @param {Integer} times Delay time (in microsecond) between patterns. * @param {Integer} duration Duration of animation. * @param {Function} callback Callback after animation. * @example * var data = ["080c0effff0e0c08", "387cfefe82443800", "40e0e0e07f030604"]; * matrix.on("0000000000000000"); * matrix.animate(data, 100); */ proto.animate = function (data, times, duration, callback) { var p = 0; if (typeof arguments[arguments.length - 1] === 'function') { callback = arguments[arguments.length - 1]; } else { callback = function () {}; } var run = function () { this.on(data[p++ % data.length]); this._timer = setTimeout(run, times); }.bind(this); var stop = function () { clearTimeout(this._timer); callback(); }.bind(this); if (times && times > 0) { run(); } if (duration && duration > 0) { this._timerDuration = setTimeout(stop, duration); } }; /** * Stop displaying animated pattern. * * @method animateStop */ proto.animateStop = function () { clearTimeout(this._timer); clearTimeout(this._timerDuration); }; scope.module.Max7219 = Max7219; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var ADXL345Event = { /** * Fires when the accelerometer senses a value change. * * @event ADXL234Event.MESSAGE */ MESSAGE: 'message' }; /** * The ADXL345 class. * * ADXL345 is a small, thin, ultralow power, 3-axis accelerometer. * * @namespace webduino.module * @class ADXL345 * @constructor * @param {webduino.Board} board The board that the ADXL345 accelerometer is attached to. * @extends webduino.Module */ function ADXL345(board) { Module.call(this); this._board = board; this._baseAxis = 'z'; this._sensitive = 10; this._detectTime = 50; this._messageHandler = onMessage.bind(this); this._init = false; this._info = { x: 0, y: 0, z: 0, fXg: 0, fYg: 0, fZg: 0 }; this._callback = function () {}; this._board.send([0xf0, 0x04, 0x0b, 0x00, 0xf7]); } function onMessage(event) { var msg = event.message; var msgPort = [0x04, 0x0b, 0x04]; var stus = true; var x, y, z; if (msg.length !== 9) { return false; } msgPort.forEach(function (val, idx) { if (val !== msg[idx]) { stus = false; } }); if (!stus) { return false; } x = (msg[3] << 8 | msg[4]) - 1024; y = (msg[5] << 8 | msg[6]) - 1024; z = (msg[7] << 8 | msg[8]) - 1024; this.emit(ADXL345Event.MESSAGE, x, y, z); } function calcFixed(base, data, fixedInfo) { Object.getOwnPropertyNames(data).forEach(function (key) { fixedInfo[key] = data[key]; if (key === base) { if (data[key] > 0) { fixedInfo[key] = data[key] - 256; } else { fixedInfo[key] = data[key] + 256; } } }); } function estimateRollandPitch(x, y, z, fXg, fYg, fZg) { var alpha = 0.5; var roll, pitch; // Low Pass Filter fXg = x * alpha + (fXg * (1.0 - alpha)); fYg = y * alpha + (fYg * (1.0 - alpha)); fZg = z * alpha + (fZg * (1.0 - alpha)); // Roll & Pitch Equations roll = (Math.atan2(-fYg, fZg) * 180.0) / Math.PI; pitch = (Math.atan2(fXg, Math.sqrt(fYg * fYg + fZg * fZg)) * 180.0) / Math.PI; roll = roll.toFixed(2); pitch = pitch.toFixed(2); return { roll: roll, pitch: pitch, fXg: fXg, fYg: fYg, fZg: fZg }; } ADXL345.prototype = proto = Object.create(Module.prototype, { constructor: { value: ADXL345 }, /** * The state indicating whether the accelerometer is detecting. * * @attribute state * @type {String} `on` or `off` */ state: { get: function () { return this._state; }, set: function (val) { this._state = val; } } }); /** * Start detection. * * @method detect * @param {Function} [callback] Detection callback. */ /** * Start detection. * * @method on * @param {Function} [callback] Detection callback. * @deprecated `on()` is deprecated, use `detect()` instead. */ proto.detect = proto.on = function(callback) { var _this = this; this._board.send([0xf0, 0x04, 0x0b, 0x01, 0xf7]); if (typeof callback !== 'function') { callback = function () {}; } this._callback = function (x, y, z) { var info = _this._info; var rt; if (!_this._init) { _this._init = true; calcFixed(this._baseAxis, { x: x, y: y, z: z }, info); } x -= info.x; y -= info.y; z -= info.z; rt = estimateRollandPitch(x, y, z, info.fXg, info.fYg, info.fZg); ['fXg', 'fYg', 'fZg'].forEach(function (val) { info[val] = rt[val]; }); // uint : mg -> g x = (x / 256).toFixed(2); y = (y / 256).toFixed(2); z = (z / 256).toFixed(2); callback(x, y, z, rt.roll, rt.pitch); }; this._state = 'on'; this._board.on(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.addListener(ADXL345Event.MESSAGE, this._callback); }; /** * Stop detection. * * @method off */ proto.off = function () { this._state = 'off'; this._board.send([0xf0, 0x04, 0x0b, 0x02, 0xf7]); this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.removeListener(ADXL345Event.MESSAGE, this._callback); this._callback = null; }; /** * Reset detection value. * * @method refresh */ proto.refresh = function () { this._init = false; if (this._init === true) { this._info = { x: 0, y: 0, z: 0, fXg: 0, fYg: 0, fZg: 0 }; } }; /** * Set the base axis for calculation. * * @method setBaseAxis * @param {String} axis Axis to be set to, either `x`, `y`, or `z`. */ proto.setBaseAxis = function (val) { this._baseAxis = val; }; /** * Set detection sensitivity. * * @method setSensitivity * @param {Number} sensitivity Detection sensitivity. */ proto.setSensitivity = function (sensitive) { if (sensitive !== this._sensitive) { this._sensitive = sensitive; this._board.send([0xf0, 0x04, 0x0b, 0x03, sensitive, 0xf7]); } }; /** * Set detecting time period. * * @method setDetectTime * @param {Number} detectTime The time period for detecting, in ms. */ proto.setDetectTime = function (detectTime) { if (detectTime !== this._detectTime) { this._detectTime = detectTime; this._board.send([0xf0, 0x04, 0x0b, 0x04, detectTime, 0xf7]); } }; scope.module.ADXL345 = ADXL345; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var HX711_MESSAGE = [0x04, 0x15]; var HX711Event = { /** * Fires when the value of weight has changed. * * @event HX711.MESSAGE */ MESSAGE: 'message' }; /** * The HX711 Class. * * HX711 is a precision 24-bit analogto-digital converter (ADC) designed for weigh scales. * * @namespace webduino.module * @class HX711 * @constructor * @param {webduino.Board} board The board that the IRLed is attached to. * @param {Integer} sckPin The pin that Serial Clock Input is attached to. * @param {Integer} dtPin The pin that Data Output is attached to. * @extends webduino.Module */ function HX711(board, sckPin, dtPin) { Module.call(this); this._board = board; this._dt = !isNaN(dtPin) ? board.getDigitalPin(dtPin) : dtPin; this._sck = !isNaN(sckPin) ? board.getDigitalPin(sckPin) : sckPin; this._init = false; this._weight = 0; this._callback = function() {}; this._messageHandler = onMessage.bind(this); this._board.send([0xf0, 0x04, 0x15, 0x00, this._sck._number, this._dt._number, 0xf7 ]); } function onMessage(event) { var msg = event.message; if (msg[0] == HX711_MESSAGE[0] && msg[1] == HX711_MESSAGE[1]) { this.emit(HX711Event.MESSAGE, msg.slice(2)); } } HX711.prototype = proto = Object.create(Module.prototype, { constructor: { value: HX711 }, /** * The state indicating whether the module is measuring. * * @attribute state * @type {String} `on` or `off` */ state: { get: function() { return this._state; }, set: function(val) { this._state = val; } } }); /** * Start detection. * * @method measure * @param {Function} [callback] Callback after starting detection. */ /** * Start detection. * * @method on * @param {Function} [callback] Callback after starting detection. * @deprecated `on()` is deprecated, use `measure()` instead. */ proto.measure = proto.on = function(callback) { var _this = this; this._board.send([0xf0, 0x04, 0x15, 0x01, 0xf7]); if (typeof callback !== 'function') { callback = function() {}; } this._callback = function(rawData) { var weight = ''; for (var i = 0; i < rawData.length; i++) { weight += (rawData[i] - 0x30); } _this._weight = parseFloat(weight); callback(_this._weight); }; this._state = 'on'; this._board.on(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.addListener(HX711Event.MESSAGE, this._callback); }; /** * Stop detection. * * @method off */ proto.off = function() { this._state = 'off'; this._board.send([0xf0, 0x04, 0x15, 0x02, 0xf7]); this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.removeListener(HX711Event.MESSAGE, this._callback); this._callback = null; }; scope.module.HX711 = HX711; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var proto; var _textSize = 2; var _cursorX = 0; var _cursorY = 0; var sendLength = 50; var sendArray = []; var sending = false; var sendAck = ''; var sendCallback; var Module = scope.Module; var BoardEvent = scope.BoardEvent; function SSD1306(board) { Module.call(this); this._board = board; board.send([0xF0, 0x04, 0x01, 0x0, 0xF7]); board.send([0xF0, 0x04, 0x01, 0x02, _cursorX, _cursorY, 0xF7]); board.send([0xF0, 0x04, 0x01, 0x03, _textSize, 0xF7]); board.send([0xF0, 0x04, 0x01, 0x01, 0xF7]); board.on(BoardEvent.SYSEX_MESSAGE, function () { sending = false; }); startQueue(board); } SSD1306.prototype = proto = Object.create(Module.prototype, { constructor: { value: SSD1306 }, textSize: { get: function () { return _textSize; }, set: function (val) { this._board.send([0xF0, 0x04, 0x01, 0x03, val, 0xF7]); _textSize = val; } }, cursorX: { get: function () { return _cursorX; }, set: function (val) { _cursorX = val; } }, cursorY: { get: function () { return _cursorY; }, set: function (val) { _cursorY = val; } } }); proto.clear = function () { this._board.send([0xF0, 0x04, 0x01, 0x01, 0xF7]); }; proto.drawImage = function (num) { this._board.send([0xF0, 0x04, 0x01, 0x05, num, 0xF7]); }; proto.render = function () { this._board.send([0xF0, 0x04, 0x01, 0x06, 0xF7]); }; proto.save = function (data, callback) { sendCallback = callback; for (var i = 0; i < data.length; i = i + sendLength) { var chunk = data.substring(i, i + sendLength); saveChunk(i / 2, chunk); } sendArray.push({ 'obj': {}, 'ack': 0 }); }; function saveChunk(startPos, data) { var CMD = [0xf0, 0x04, 0x01, 0x0A]; var raw = []; raw = raw.concat(CMD); var n = '0000' + startPos.toString(16); n = n.substring(n.length - 4); for (var i = 0; i < 4; i++) { raw.push(n.charCodeAt(i)); } raw.push(0xf7); // send Data // CMD = [0xf0, 0x04, 0x01, 0x0B]; raw = raw.concat(CMD); for (i = 0; i < data.length; i++) { raw.push(data.charCodeAt(i)); } raw.push(0xf7); sendArray.push({ 'obj': raw, 'ack': 0x0B }); } function startQueue(board) { setInterval(function () { if (sending || sendArray.length == 0) { return; } sending = true; var sendObj = sendArray.shift(); sendAck = sendObj.ack; if (sendAck > 0) { board.send(sendObj.obj); } else { sending = false; sendCallback(); } }, 0); } proto.print = function (cursorX, cursorY, str) { var len = arguments.length; if (len == 3) { _cursorX = cursorX; _cursorY = cursorY; this._board.send([0xF0, 0x04, 0x01, 0x02, cursorX, cursorY, 0xF7]); } else { str = cursorX; this._board.send([0xF0, 0x04, 0x01, 0x02, _cursorX, _cursorY, 0xF7]); } var strCMD = [0xF0, 0x04, 0x01, 0x04]; for (var i = 0; i < str.length; i++) { strCMD.push(str.charCodeAt(i)); } strCMD.push(0xF7); this._board.send(strCMD); }; scope.module.SSD1306 = SSD1306; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var BARCODE_MESSAGE = [0x04, 0x16]; var BarcodeEvent = { /** * Fires when the barcode scanner scans a code. * * @event BarcodeEvent.MESSAGE */ MESSAGE: 'message' }; /** * The Barcode class. * * @namespace webduino.module * @class Barcode * @constructor * @param {webduino.Board} board The board the barcode scanner is attached to. * @param {webduino.Pin | Number} rxPin Receivin pin (number) the barcode scanner is connected to. * @param {webduino.Pin | Number} txPin Transmitting pin (number) the barcode scanner is connected to. * @extends webduino.Module */ function Barcode(board, rxPin, txPin) { Module.call(this); this._board = board; this._rx = !isNaN(rxPin) ? board.getDigitalPin(rxPin) : rxPin; this._tx = !isNaN(txPin) ? board.getDigitalPin(txPin) : txPin; this._init = false; this._scanData = ''; this._callback = function () {}; this._messageHandler = onMessage.bind(this); this._board.send([0xf0, 0x04, 0x16, 0x00, this._rx._number, this._tx._number, 0xf7 ]); } function onMessage(event) { var msg = event.message; if (msg[0] == BARCODE_MESSAGE[0] && msg[1] == BARCODE_MESSAGE[1]) { this.emit(BarcodeEvent.MESSAGE, msg.slice(2)); } } Barcode.prototype = proto = Object.create(Module.prototype, { constructor: { value: Barcode }, /** * The state indicating whether the module is scanning. * * @attribute state * @type {String} 'on' or 'off' */ state: { get: function () { return this._state; }, set: function (val) { this._state = val; } } }); /** * Start scanning. * * @method scan * @param {Function} [callback] Scanning callback. */ /** * Start scanning. * * @method on * @param {Function} [callback] Scanning callback. * @deprecated `on()` is deprecated, use `scan()` instead. */ proto.scan = proto.on = function(callback) { var _this = this; this._board.send([0xf0, 0x04, 0x16, 0x01, 0xf7]); if (typeof callback !== 'function') { callback = function () {}; } this._callback = function (rawData) { var scanData = ''; for (var i = 0; i < rawData.length; i++) { scanData += String.fromCharCode(rawData[i]); } _this._scanData = scanData; callback(_this._scanData); }; this._state = 'on'; this._board.on(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.addListener(BarcodeEvent.MESSAGE, this._callback); }; /** * Stop scanning. * * @method off */ proto.off = function () { this._state = 'off'; this._board.send([0xf0, 0x04, 0x16, 0x02, 0xf7]); this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.removeListener(BarcodeEvent.MESSAGE, this._callback); this._callback = null; }; scope.module.Barcode = Barcode; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, proto; /** * The IRLed Class. * * IR LED (Infrared LED) is widely used for remote controls and night-vision cameras. * * @namespace webduino.module * @class IRLed * @constructor * @param {webduino.Board} board The board that the IRLed is attached to. * @param {String} encode Encode which IRLed used. * @extends webduino.Module */ function IRLed(board, encode) { Module.call(this); this._board = board; this._encode = encode; this._board.send([0xf4, 0x09, 0x03, 0xe9, 0x00, 0x00]); } IRLed.prototype = proto = Object.create(Module.prototype, { constructor: { value: IRLed } }); /** * Send IR code. * * @method send * @param {String} code Hexadecimal String to send. */ proto.send = function (code) { var aryCode = [0x09, 0x04]; var ary; code = code || this._encode; if (code) { ary = code.match(/\w{2}/g); // data length aryCode.push(ary.length * 8); ary.forEach(function (val) { for (var i = 0, len = val.length; i < len; i++) { aryCode.push(val.charCodeAt(i)); } }); this._board.sendSysex(0x04, aryCode); } }; /** * Update code. * * @method updateEncode * @param {String} code Hexadecimal to update. */ proto.updateEncode = function (code) { this._encode = code; }; scope.module.IRLed = IRLed; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var IRRecvEvent = { /** * Fires when receiving data. * * @event IRRecvEvent.MESSAGE */ MESSAGE: 'message', /** * Fires when error occured while receiving data. * * @event IRRecvEvent.MESSAGE_ERROR */ MESSAGE_ERROR: 'messageError' }; /** * The IRRecv Class. * * @namespace webduino.module * @class IRRecv * @constructor * @param {webduino.Board} board The board that the IRLed is attached to. * @param {Integer} pin The pin that the IRLed is connected to. * @extends webduino.Module */ function IRRecv(board, pin) { Module.call(this); this._board = board; this._pin = pin; this._messageHandler = onMessage.bind(this); this._recvCallback = function () {}; this._recvErrorCallback = function () {}; this._board.send([0xf0, 0x04, 0x0A, 0x01, 0xf7]); } function onMessage(event) { var recvChk = [0x04, 0x10]; var msg = event.message; var data = msg.slice(2); var str = ''; var i, tp, len; for (i = 0, len = recvChk.length; i < len; i++) { if (recvChk[i] !== msg[i]) { return false; } } for (i = 0; i < data.length; i++) { tp = String.fromCharCode(data[i]); str += tp.toLowerCase(); } if (str !== 'ffffffff') { this.emit(IRRecvEvent.MESSAGE, str); } else { this.emit(IRRecvEvent.MESSAGE_ERROR, str, msg); } } IRRecv.prototype = proto = Object.create(Module.prototype, { constructor: { value: IRRecv }, /** * The state indicating whether the IRLed is receiving. * * @attribute state * @type {String} `on` or `off` */ state: { get: function () { return this._state; }, set: function (val) { this._state = val; } } }); /** * Start detection. * * @method receive * @param {Function} [callback] Detection callback. * @param {Function} [errorCallback] Error callback while Detection. */ /** * Start detection. * * @method on * @param {Function} [callback] Detection callback. * @param {Function} [errorCallback] Error callback while Detection. * @deprecated `on()` is deprecated, use `receive()` instead. */ proto.receive = proto.on = function (callback, errorCallback) { var aryCode = [0xf0, 0x04, 0x0A, 0x00]; if (typeof callback !== 'function') { callback = function () {}; } if (typeof errorCallback !== 'function') { errorCallback = function () {}; } if (this._pin) { aryCode.push(this._pin.number, 0xf7); this._board.send(aryCode); this._state = 'on'; this._recvCallback = function (value) { callback(value); }; this._recvErrorCallback = function (value, msg) { errorCallback(value, msg); }; this._board.on(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.addListener(IRRecvEvent.MESSAGE, this._recvCallback); this.addListener(IRRecvEvent.MESSAGE_ERROR, this._recvErrorCallback); } }; /** * Stop detection. * * @method off */ proto.off = function () { this._board.send([0xf0, 0x04, 0x0A, 0x01, 0xf7]); this._state = 'off'; this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.removeListener(IRRecvEvent.MESSAGE, this._recvCallback); this.removeListener(IRRecvEvent.MESSAGE_ERROR, this._recvErrorCallback); this._recvCallback = null; this._recvErrorCallback = null; }; scope.module.IRRecv = IRRecv; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module; var BoardEvent = scope.BoardEvent; var Button = scope.module.Button; var ButtonEvent = scope.module.ButtonEvent; var JoystickEvent = { MESSAGE: 'message' }; function Joystick(board, analogPinX, analogPinY, pinZ) { Module.call(this); this._board = board; this._pinX = Number(analogPinX); this._pinY = Number(analogPinY); this._pinZ = pinZ; this._data = { x: 0, y: 0, z: 0 }; board.enableAnalogPin(this._pinX); board.enableAnalogPin(this._pinY); board.addListener(BoardEvent.ANALOG_DATA, onMessage.bind(this)); this._button = new Button(board, pinZ); this._button.on(ButtonEvent.PRESS, onPinChange.bind(this)); this._button.on(ButtonEvent.RELEASE, onPinChange.bind(this)); } function onMessage(event) { var pin = event.pin; if (pin.analogNumber !== this._pinX && pin.analogNumber !== this._pinY) { return false; } if (pin.analogNumber === this._pinX) { this._data.x = pin.value; } if (pin.analogNumber === this._pinY) { this._data.y = pin.value; } this.emit(JoystickEvent.MESSAGE, this._data.x, this._data.y, this._data.z); } function onPinChange() { this._data.z = this._button._pin.value; } Joystick.prototype = Object.create(Module.prototype, { constructor: { value: Joystick } }); scope.module.JoystickEvent = JoystickEvent; scope.module.Joystick = Joystick; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, PinEvent = scope.PinEvent, Pin = scope.Pin, proto; var MQ2Event = { MESSAGE: 'message', DETECTED: 'detected', ENDED: 'ended' }; function MQ2(board, analogPinNumber, pin) { Module.call(this); this._board = board; if (analogPinNumber) { this._pinNumber = Number(analogPinNumber); this._messageHandler = onMessage.bind(this); } if (pin) { this._pin = pin; board.setDigitalPinMode(pin.number, Pin.DIN); this._pin.value = Pin.LOW; this._pin.on(PinEvent.CHANGE, onPinChange.bind(this)); } } function onMessage(event) { var pin = event.pin; if (this._pinNumber !== pin.analogNumber) { return false; } this.emit(MQ2Event.MESSAGE, pin.value); } function onPinChange(pin) { if (pin.value === Pin.HIGH) { this.emit(MQ2Event.DETECTED); } else { this.emit(MQ2Event.ENDED); } } MQ2.prototype = proto = Object.create(Module.prototype, { constructor: { value: MQ2 }, state: { get: function() { return this._state; }, set: function(val) { this._state = val; } } }); proto.on = function(callback) { if (typeof callback !== 'function') { callback = function() {}; } this._state = 'on'; this._board.enableAnalogPin(this._pinNumber); this._analogCallback = function(val) { callback(val); }; this._board.on(BoardEvent.ANALOG_DATA, this._messageHandler); this.addListener(MQ2Event.MESSAGE, this._analogCallback); }; proto.off = function() { this._state = 'off'; this._board.disableAnalogPin(this._pinNumber); this._board.removeListener(BoardEvent.ANALOG_DATA, this._messageHandler); if (this._analogCallback) { this.removeListener(MQ2Event.MESSAGE, this._analogCallback); this._analogCallback = null; } }; proto.onEvent = function(type, handler) { this.addListener(type, handler); }; proto.offEvent = function(type, handler) { this.removeListener(type, handler); }; scope.module.MQ2 = MQ2; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var PhotocellEvent = { /** * Fires when the value of brightness has changed. * * @event PhotocellEvent.MESSAGE */ MESSAGE: 'message' }; /** * The Photocell class. * * Photocell is small, inexpensive, low-power sensor that allow you to detect light. * * @namespace webduino.module * @class Photocell * @constructor * @param {webduino.Board} board Board that the photocell is attached to. * @param {Integer} analogPinNumber The pin that the photocell is connected to. * @extends webduino.Module */ function Photocell(board, analogPinNumber) { Module.call(this); this._board = board; this._pinNumber = Number(analogPinNumber); this._messageHandler = onMessage.bind(this); } function onMessage(event) { var pin = event.pin; if (this._pinNumber !== pin.analogNumber) { return false; } this.emit(PhotocellEvent.MESSAGE, pin.value); } Photocell.prototype = proto = Object.create(Module.prototype, { constructor: { value: Photocell }, /** * The state indicating whether the module is measuring. * * @attribute state * @type {String} `on` or `off` */ state: { get: function () { return this._state; }, set: function (val) { this._state = val; } } }); /** * Start detection. * * @method measure * @param {Function} [callback] Callback after starting detection. */ /** * Start detection. * * @method on * @param {Function} [callback] Callback after starting detection. * @deprecated `on()` is deprecated, use `measure()` instead. */ proto.measure = proto.on = function(callback) { this._board.enableAnalogPin(this._pinNumber); if (typeof callback !== 'function') { callback = function () {}; } this._callback = function (val) { callback(val); }; this._state = 'on'; this._board.on(BoardEvent.ANALOG_DATA, this._messageHandler); this.addListener(PhotocellEvent.MESSAGE, this._callback); }; /** * Stop detection. * * @method off */ proto.off = function () { this._state = 'off'; this._board.disableAnalogPin(this._pinNumber); this._board.removeListener(BoardEvent.ANALOG_DATA, this._messageHandler); this.removeListener(PhotocellEvent.MESSAGE, this._callback); this._callback = null; }; scope.module.Photocell = Photocell; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var PotEvent = { MESSAGE: 'message' }; function Pot(board, analogPinNumber) { Module.call(this); this._board = board; this._pinNumber = Number(analogPinNumber); this._messageHandler = onMessage.bind(this); } function onMessage(event) { var pin = event.pin; if (this._pinNumber !== pin.analogNumber) { return false; } this.emit(PotEvent.MESSAGE, pin.value); } Pot.prototype = proto = Object.create(Module.prototype, { constructor: { value: Pot }, state: { get: function() { return this._state; }, set: function(val) { this._state = val; } } }); proto.on = function(callback) { this._board.enableAnalogPin(this._pinNumber); if (typeof callback !== 'function') { callback = function() {}; } this._callback = function(val) { callback(val); }; this._state = 'on'; this._board.on(BoardEvent.ANALOG_DATA, this._messageHandler); this.addListener(PotEvent.MESSAGE, this._callback); }; proto.off = function() { this._state = 'off'; this._board.disableAnalogPin(this._pinNumber); this._board.removeListener(BoardEvent.ANALOG_DATA, this._messageHandler); this.removeListener(PotEvent.MESSAGE, this._callback); this._callback = null; }; scope.module.Pot = Pot; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var RFIDEvent = { /** * Fires when the RFID entered. * * @event RFIDEvent.ENTER */ ENTER: 'enter', /** * Fires when the RFID leaved. * * @event RFIDEvent.LEAVE */ LEAVE: 'leave' }; /** * The RFID class. * * RFID reader is used to track nearby tags by wirelessly reading a tag's unique ID. * * @namespace webduino.module * @class RFID * @constructor * @param {webduino.Board} board Board that the RFID is attached to. * @extends webduino.Module */ function RFID(board) { Module.call(this); this._board = board; this._isReading = false; this._enterHandlers = []; this._leaveHandlers = []; this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.BEFOREDISCONNECT, this.destroy.bind(this)); this._board.on(BoardEvent.ERROR, this.destroy.bind(this)); this._board.send([0xf0, 0x04, 0x0f, 0x00, 0xf7]); } function onMessage(event) { var _this = this; var msg = event.message; var val; if (!msg.length) { return false; } if (msg.length === 1) { _this._leaveHandlers.forEach(function (fn) { fn.call(_this, val); }); _this.emit(RFIDEvent.LEAVE, val); val = null; } else { val = String.fromCharCode.apply(null, msg); _this._enterHandlers.forEach(function (fn) { fn.call(_this, val); }); _this.emit(RFIDEvent.ENTER, val); } } RFID.prototype = proto = Object.create(Module.prototype, { constructor: { value: RFID }, /** * The state indicating whether the module is reading. * * @attribute isReading * @type {Boolean} isReading * @readOnly */ isReading: { get: function () { return this._isReading; } } }); /** * Start reading RFID. * * @method read * @param {Function} [enterHandler] Callback when RFID entered. * @param {Function} [leaveHandler] Callback when RFID leaved. */ proto.read = function (enterHandler, leaveHandler) { if (!this._isReading) { this._board.send([0xf0, 0x04, 0x0f, 0x01, 0xf7]); this._board.on(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this._isReading = true; } if (typeof enterHandler === 'function') { this._enterHandlers.push(enterHandler); } if (typeof leaveHandler === 'function') { this._leaveHandlers.push(leaveHandler); } }; /** * Stop reading RFID. * * @method stopRead */ proto.stopRead = function () { if (this._isReading) { this._board.send([0xf0, 0x04, 0x0f, 0x02, 0xf7]); this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this._isReading = false; this._enterHandlers = []; this._leaveHandlers = []; } }; /** * Remove listener. * * @method off * @param {String} evtType Type of event. * @param {Function} handler Callback function. */ proto.off = function (evtType, handler) { this.removeListener(evtType, handler); }; /** * Stop reading RFID and remove all listeners. * * @method destroy */ proto.destroy = function () { this.stopRead(); this.removeAllListeners(RFIDEvent.ENTER); this.removeAllListeners(RFIDEvent.LEAVE); }; scope.module.RFIDEvent = RFIDEvent; scope.module.RFID = RFID; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var SoilEvent = { /** * Fires when the value of humidity has changed. * * @event PhotocellEvent.MESSAGE */ MESSAGE: 'message' }; /** * The Soil class. * * @namespace webduino.module * @class Soil * @constructor * @param {webduino.Board} board Board that the soil is attached to. * @param {Integer} analogPinNumber The pin that soil is attached to. * @extends webduino.Module */ function Soil(board, analogPinNumber) { Module.call(this); this._board = board; this._pinNumber = Number(analogPinNumber); this._messageHandler = onMessage.bind(this); } function formatter(val) { val = Math.round(val * 10000) / 100; return val; } function onMessage(event) { var pin = event.pin; if (this._pinNumber !== pin.analogNumber) { return false; } this.emit(SoilEvent.MESSAGE, formatter(pin.value)); } Soil.prototype = proto = Object.create(Module.prototype, { constructor: { value: Soil }, /** * The state indicating whether the module is scanning. * * @attribute state * @type {String} `on` or `off` */ state: { get: function() { return this._state; }, set: function(val) { this._state = val; } } }); /** * Start detection. * * @method measure * @param {Function} [callback] Callback after starting detection. */ /** * Start detection. * * @method on * @param {Function} [callback] Callback after starting detection. * @deprecated `on()` is deprecated, use `measure()` instead. */ proto.measure = proto.on = function(callback) { this._board.enableAnalogPin(this._pinNumber); if (typeof callback !== 'function') { callback = function() {}; } this._callback = function(val) { callback(val); }; this._state = 'on'; this._board.on(BoardEvent.ANALOG_DATA, this._messageHandler); this.addListener(SoilEvent.MESSAGE, this._callback); }; /** * Stop detection. * * @method off */ proto.off = function() { this._state = 'off'; this._board.disableAnalogPin(this._pinNumber); this._board.removeListener(BoardEvent.ANALOG_DATA, this._messageHandler); this.removeListener(SoilEvent.MESSAGE, this._callback); this._callback = null; }; scope.module.Soil = Soil; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var G3_MESSAGE = [0x04, 0x10], MIN_READ_INTERVAL = 1000, MIN_RESPONSE_TIME = 30, RETRY_INTERVAL = 6000; var G3Event = { READ: 'read', READ_ERROR: 'readError' }; function G3(board, rx, tx) { Module.call(this); this._type = 'G3'; this._board = board; this._rx = rx; this._tx = tx; this._pm25 = null; this._pm10 = null; this._readTimer = null; this._readCallback = function() {}; this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopRead.bind(this)); this._messageHandler = onMessage.bind(this); this._board.on(BoardEvent.ERROR, this.stopRead.bind(this)); this._board.sendSysex(G3_MESSAGE[0], [G3_MESSAGE[1], 0, rx.number, tx.number]); } function onMessage(event) { var message = event.message; if (message[0] !== G3_MESSAGE[0] || message[1] !== G3_MESSAGE[1]) { return; } else { processG3Data(this, message); } } function processG3Data(self, data) { var str = '', i; for(i = 2; i < data.length; i++){ str += String.fromCharCode(data[i]); } str = str.split(','); self._lastRecv = Date.now(); self.emit(G3Event.READ, str[0], str[1]); } G3.prototype = proto = Object.create(Module.prototype, { constructor: { value: G3 }, pm25: { get: function() { return this._pm25; } }, pm10: { get: function() { return this._pm10; } } }); proto.read = function(callback, interval) { var self = this, timer; self.stopRead(); if (typeof callback === 'function') { self._readCallback = function(pm25, pm10) { self._pm25 = pm25; self._pm10 = pm10; callback({ pm25: pm25, pm10: pm10 }); }; self._board.on(BoardEvent.SYSEX_MESSAGE, self._messageHandler); self.on(G3Event.READ, self._readCallback); timer = function() { self._board.sendSysex(G3_MESSAGE[0], [G3_MESSAGE[1], 3]); if (interval) { interval = Math.max(interval, MIN_READ_INTERVAL); if (self._lastRecv === null || Date.now() - self._lastRecv < 5 * interval) { self._readTimer = setTimeout(timer, interval); } else { self.stopRead(); setTimeout(function() { self.read(callback, interval); }, RETRY_INTERVAL); } } }; timer(); } else { return new Promise(function(resolve) { self.read(function(data) { self._pm25 = data.pm25; self._pm10 = data.pm10; setTimeout(function() { resolve(data); }, MIN_RESPONSE_TIME); }); }); } }; proto.stopRead = function() { this.removeListener(G3Event.READ, this._readCallback); this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this._lastRecv = null; if (this._readTimer) { clearTimeout(this._readTimer); delete this._readTimer; } }; scope.module.G3Event = G3Event; scope.module.G3 = G3; })); +(function (global, factory) { if (typeof exports === 'undefined') { factory(global.webduino || {}); } else { module.exports = factory; } }(this, function (scope) { 'use strict'; var Module = scope.Module, BoardEvent = scope.BoardEvent, proto; var StepperEvent = { MESSAGE: 'message' }; function Stepper(board, config) { Module.call(this); this._board = board; this._stepperNumber = Number(config.stepperNumber); this._interface = Number(config.interface); this._stepPerRevolution = Number(config.stepsPerRevolution); this._pin1 = Number(config.pin1); this._pin2 = Number(config.pin2); this._pin3 = Number(config.pin3); this._pin4 = Number(config.pin4); this._messageHandler = onMessage.bind(this); var val = transferNumber(this._stepPerRevolution, 2); var cmd = [].concat(0xF0, 0x72, 0x00, this._stepperNumber, this._interface, val, this._pin1, this._pin3, this._pin2, this._pin4, 0xF7); this._board.send(cmd); } function onMessage(event) { var msg = event.message; if (msg[0] !== Number(0x72)) { return false; } this.emit(StepperEvent.MESSAGE, { status: true, stepperNumber: msg[1] }); } // 2048 => [0, 16] => [0x00, 0x10] function transferNumber(value, num) { var str = value.toString(2); var ary = []; var end = str.length; var start; for (var i = 1; i < num + 1; i++) { start = -7 * i; ary.push(str.slice(start, end)); end = start; } ary.forEach(function(val, idx, target) { val = parseInt(val, 2); val > 0 || (val = 0); target[idx] = val; }); return ary; } Stepper.prototype = proto = Object.create(Module.prototype, { constructor: { value: Stepper } }); proto.on = function(command, callback) { var _this = this; var stepperNumber = Number(command.stepperNumber) || 0; var direction = Number(command.direction) || 0; var stepNumber = Number(command.stepNumber) || 0; var speed = Number(command.speed) || 10; var speedAry = []; var stepNumberAry = []; var cmd; speedAry = transferNumber(speed, 2); stepNumberAry = transferNumber(stepNumber, 3); cmd = [].concat(0xF0, 0x72, 0x01, stepperNumber, direction, stepNumberAry, speedAry, 0xF7); this._board.send(cmd); if (typeof callback !== 'function') { callback = function() {}; } this._callback = function(val) { _this.off(); callback(val); }; this._board.on(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.addListener(StepperEvent.MESSAGE, this._callback); }; proto.off = function() { this._board.removeListener(BoardEvent.SYSEX_MESSAGE, this._messageHandler); this.removeListener(StepperEvent.MESSAGE, this._callback); this._callback = null; }; scope.module.Stepper = Stepper; }));
// Signup.js import React from 'react'; import { Link, browserHistory } from 'react-router'; export default class Signup extends React.Component { constructor(props) { super(props); this.state = { email: '', password: '', confirmPassword: '' } this.signupUser = this.signupUser.bind(this); this.getToken = this.getToken.bind(this) } signupUser(e) { let that = this; if(this.state.email === '' || this.state.password === '') { return alert('Please use valid email and password'); } else if(this.state.password !== this.state.confirmPassword) { return alert('Passwords do not match'); } let userObj = { email: this.state.email, password: this.state.password } let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if(xhr.status === 200 && xhr.readyState === 4) { that.getToken(userObj); } } xhr.open('POST', '/api/user'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(userObj)); } getToken(userData) { let that = this; let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if(xhr.status === 302 && xhr.readyState === 4) { let userData = JSON.parse(xhr.responseText); localStorage.setItem('token', userData.token); localStorage.setItem('userId', userData.id); browserHistory.push('dashboard'); } } xhr.open('POST', '/login'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(userData)); } updateInput(e) { let email = this.refs.signupEmail.value; let password = this.refs.signupPassword.value; let confirmPassword = this.refs.signupConfirm.value; this.setState({ email, password, confirmPassword }) } render() { return( <div> <h4>Sign up</h4> <div className="form-group"> <input ref="signupEmail" placeholder="email" onChange={(e) => {this.updateInput(e)}} /> <input ref="signupPassword" type="password" placeholder="password" onChange={(e) => {this.updateInput(e)}} /> <input ref="signupConfirm" type="password" placeholder="confirm-password" onChange={(e) => {this.updateInput(e)}} /> <button className="btn btn-default" onClick={(e) => {this.signupUser(e)}}>Enter</button> </div> </div> ) } }
define([], function () { 'use strict'; return function ($scope, $stateParams, teamSettingService, $state, $loading, $toast, $dialog, $rootScope, $ionicHistory, $filter, $ionicPopup) { var id = $stateParams.id; var isEdit = $state.current.name === 'teamSetting-editSetting'; var pluginGroup = $filter('pluginGroup'); $scope.vm = { title: isEdit? '็ผ–่พ‘ๆŽˆๆƒ' : 'ๆ–ฐๅขžๆŽˆๆƒ', actionTitle: $stateParams.title, staffEdit: false, personEdit: false, isEdit: isEdit, staffs: [], persons: [] }; //ๅŽŸๅง‹ๅˆๅง‹ๅŒ–ๆ•ฐๆฎ $scope.setting = { staffs: [], persons: [] }; $scope.init = function (){ if(isEdit){ $loading.show(); teamSettingService.findSetting(id) .then(function (result){ $scope.setting = result; }) .catch(function (err){ $toast.error(err); }) .finally(function(){ $loading.hide(); }); } }; $scope.$watchCollection('setting.staffs', function () { $scope.vm.staffs = pluginGroup($scope.setting.staffs, 4); }); $scope.$watchCollection('setting.persons', function () { $scope.vm.persons = pluginGroup($scope.setting.persons, 4); }); $scope.saveSetting = function (){ if(!angular.isArray($scope.setting.staffs) || $scope.setting.staffs.length === 0){ $toast.warning("ๆŽˆๆƒๅฏน่ฑกไธ่ƒฝไธบ็ฉบ"); return; } var staffIds = []; var personIds = []; angular.forEach($scope.setting.staffs,function(item){ staffIds.push(item.id); }); angular.forEach($scope.setting.persons,function(item){ personIds.push(item.id); }); if(isEdit){ teamSettingService.saveSetting(id, staffIds, personIds) .then(function(result){ $ionicHistory.goBack(); }) .catch(function(err){ $toast.error(err); }); }else{ teamSettingService.addSetting(id, staffIds, personIds) .then(function(result){ $ionicHistory.goBack(); }) .catch(function(err){ $toast.error(err); }); } }; $scope.showTeamStaffs = function (type){ //ๅผนๅ‡บๅ…ฌๅธๆˆๅ‘˜ๅฏน่ฏๆก† $scope.dialogOptions = { checkedItems: angular.copy($scope.setting[type]), return: function(value){ if(angular.isArray(value)){ $scope.setting[type] = value; } } }; $dialog.showPluginDialog('teamSetting', 'selectStaff', $scope); }; $scope.onItemRemove = function (type, item){ var source = $scope.setting[type]; for(var i=source.length - 1; i>=0; i--){ if(source[i].id === item.id){ source.splice(i,1); break; } } }; $scope.onDelete = function (){ $ionicPopup.confirm({ title: '็กฎๅฎšๅˆ ้™คๆŽˆๆƒๅ—', template: 'ๅˆ ้™คๆŽˆๆƒๅŽๆŽˆๆƒๅฏน่ฑกๅฐ†ๆ— ๆณ•ไฝฟ็”จๆญคๅบ”็”จ', okText: 'ๅˆ ้™ค', okType: 'button-assertive', cancelText: 'ๅ–ๆถˆ', cancelType: 'button-stable' }) .then(function(res) { if(!res) { return; } $loading.show(); teamSettingService.removeSetting(id) .then(function (){ $ionicHistory.goBack(); }) .catch(function (err){ $toast.error(err); }) .finally(function () { $loading.hide(); }); }); }; }; });
/* jshint undef: true, unused: true */ /* globals angular */ /* jshint strict: true */ /* globals window */ /* globals webkitURL */ /* jshint unused:true */ "use strict"; angular.module('app', ['ngResource', 'ngRoute', 'ui.bootstrap', 'appConfigurations', 'appControllers', 'appDirectives', 'appServices']);
/** * Created by Lindon Camaj on 5/6/2016. */ var express = require("express"); var bodyParser = require('body-parser'); var server = require('./src/app'); // express server var app = express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: false})); // parse application/json app.use(bodyParser.json()); /** * Get application config and then start application */ server.Core.Utility.Json.readJson("config/config.json").then(function(config){ if(typeof config !== "undefined" && config !== null){ // start application server.start(app, config); // start server app.listen(config.app.port, function () { console.log("Server is up: " + config.app.port); }); } });
/** * Created by IvanIsrael on 08/04/2017. */ 'use strict'; const Tequila = require('mongoose').model('Tequila'); /** * Custom error throwed by create user service when user isn`t insert row * * @class ErrorInsertUser * @extends {Error} */ class ErrorInsertTequila extends Error { constructor(message) { super(message); this.message = message; this.name = this.constructor.name; this.code = 401; } } class ErrorUpdateTequila extends Error { constructor(message) { super(message); this.message = message; this.name = this.constructor.name; this.code = 401; } } class ErrorDeleteTequila extends Error { constructor(message) { super(message); this.message = message; this.name = this.constructor.name; this.code = 401; } } class TequilaService { searchTequilas (data, callback) { let limit = data.limit; let page = data.page; let query = data.query; let search = async function () { try { let tequila = Tequila.paginate(query, { page: page, limit: limit, populate: '_category', sort: 'name' }); return tequila; } catch (e) { console.log("error.search"); console.log(e); throw new ErrorInsertUser("error.update_tequila"); } }; return Promise.resolve(search()).asCallback(callback); } createTequila (data_tequila, callback) { let create = async function () { try { let tequila = Tequila(data_tequila); tequila.images.push({ path: data_tequila.main_image }); let new_tequila = await tequila.save(); console.log(new_tequila); return new_tequila; } catch (e) { console.log(e); throw new ErrorInsertUser("error.update_tequila"); } }; return Promise.resolve(create()).asCallback(callback); } updateTequila (data_tequila, tequilaId, callback) { let update = async function () { try { let tequila = Tequila.findByIdAndUpdate(tequilaId, data_tequila); console.log(tequila); return tequila; } catch (e) { console.log(e); throw new ErrorUpdateTequila("error.update_tequila"); } }; return Promise.resolve(update()).asCallback(callback); } deleteTequila (tequilaId, callback) { let delete_tequila = async function () { try { let tequila = Tequila.findByIdAndUpdate(tequilaId, { deleted: true, active: false }); console.log(tequila); return tequila; } catch (e) { console.log(e); throw new ErrorDeleteTequila("error.delete_tequila"); } }; return Promise.resolve(delete_tequila()).asCallback(callback); } infoTequila (tequilaId, callback) { let tequila_info = async function () { try { return Tequila.findOne({ _id: tequilaId, active: true }).populate('_category').lean(); } catch (e) { console.log(e); throw new ErrorDeleteTequila("error.info_tequila"); } }; return Promise.resolve(tequila_info()).asCallback(callback); } allActiveTequilas (callback) { let tequila_info = async function () { try { let tequilas = await Tequila.find({ active: true }).populate('_category').lean(); let tequilas_list = []; for (let index in tequilas) { let t = { id: tequilas[index]._id, name: tequilas[index].name, category_id: tequilas[index]._category._id, category_name: tequilas[index]._category.name, content: `${tequilas[index].quantity} ${tequilas[index].content}`, review: tequilas[index].review, stock: tequilas[index].stock, purity: tequilas[index].purity, NOM: tequilas[index].NOM, destillery: tequilas[index].distillery, price: tequilas[index].price, created: tequilas[index].created }; tequilas_list.push(t); } return tequilas_list; } catch (e) { console.log(e); throw new ErrorDeleteTequila("error.all_tequilas"); } }; return Promise.resolve(tequila_info()).asCallback(callback); } addImages(tequilaId, image, callback) { let tequila_info = async function () { try { let tequila = await Tequila.findOne({ _id: tequilaId, active: true }); console.log(tequila) tequila.images.push({ path: image }); let img = await tequila.save(); return img; } catch (e) { console.log(e); throw new ErrorInsertTequila("error.add_tequila_image"); } }; return Promise.resolve(tequila_info()).asCallback(callback); } } module.exports = TequilaService;
$(document).ready(function(){ var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition; var recognition = new SpeechRecognition(); recognition.lang = 'en-US'; recognition.continuous = true; $('#start-search').click(function(){ var resultIndex = 0; recognition.start(); recognition.onresult = function(event){ var speechQuery = event.results[resultIndex][0].transcript; resultIndex += 1; $.ajax({ url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=' + apiKey + '&format=json&nojsoncallback=1&text=' + speechQuery +'&extras=url_m&per_page=3', dataType: 'json' }).then(function(response){ response.photos.photo.forEach(function(photo){ $('#search-results').prepend("<div class='img-result'><img src='" + photo.url_m + "'</div>"); }); }).then(function(){ $('#current-search').text('Last search: ' + speechQuery); }); }; $(this).hide(); $('#end-search').show(); }); $('#end-search').click(function(){ recognition.stop(); $(this).hide(); $('#start-search').show(); }); });
// Reference to my Firebase var myFirebaseRef = new Firebase('https://<YOUR-APP>.firebaseio.com/'); // Grobal var index = 4; var maps = []; console.log('%cโš› Projection Mapping Tool: Hello geohacker! โš›', 'font-family:monospace;font-size:16px;color:darkblue;'); // Create menu icon $.fatNav(); // Menu event listner $('.fat-nav__wrapper').on('click', function(e) { console.log(e.target.text); createMapContainer(e.target.text); }); // Create container before map function createMapContainer(type) { var mapCont = $('<div>', { id: 'l-map' + index, css: { top: '50px', left: '50px' }, addClass: 'l-map' }); $('body').append(mapCont); Maptastic('l-map' + index); createMap(index, type); index += 1; } // Create map and add tile layer function createMap(index, type) { var center = [35.8, 139]; var zoom = 4; var map = L.map('l-map' + index, { zoomControl: false, attributionControl: false }).setView(center, zoom); maps.push(map); switch (type) { case 'OpenStreetMap': L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>', id: 'osm' + index }).addTo(map); break; case 'Esri Satellite': L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { maxZoom: 18, attribution: '&copy; <a href="http://www.esri.com/">Esri</a>, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community', id: 'esri-satellite' + index }).addTo(map); break; case 'Stamen Tonar': L.tileLayer('//stamen-tiles-a.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '<a id="home-link" target="_top" href="../">Map tiles</a> by <a target="_top" href="http://stamen.com">Stamen Design</a>, under <a target="_top" href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a target="_top" href="http://openstreetmap.org">OpenStreetMap</a>, under <a target="_top" href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>. | Video from <a target="_top" href="http://mazwai.com/">Mazwai</a>.', id: 'stamen-toner' + index }).addTo(map); break; } } // Create GeoJSON layer and add into maps function createGeoJSONLayer(url) { var markerIcon = L.divIcon({ className: 'svg-marker-icon', html: '<svg width="64px" height="64px" viewBox="-20 -20 64 64"><g><circle class="circles" opacity="0.4" r="6" transform="translate(0,0)"></circle></g></svg>' }); var pathStyle = { color: '#ff6500', weight: 1, opacity: 0.8, fillOpacity: 0.35, fillColor: '#ff6500' }; $.getJSON(url, function(data) { $.each(maps, function(i, map) { var geojson = L.geoJson(data, { onEachFeature: function(feature, layer) { console.log(layer.feature.geometry.type); if(layer.feature.geometry.type === 'Polygon' || layer.feature.geometry.type === 'MultiPolygon' || layer.feature.geometry.type === 'Polyline') { layer.setStyle(pathStyle); } else if(layer.feature.geometry.type === 'Point' || layer.feature.geometry.type === 'MultiPoint') { layer.setIcon(markerIcon); } else { return false; } } }); geojson.addTo(map); }); }); } // Init function initMap() { var center = [35.8, 139]; var zoom = 4; var map1 = L.map('l-map1', { zoomControl: false, attributionControl: false }).setView(center, zoom); var map2 = L.map('l-map2', { zoomControl: false, attributionControl: false }).setView(center, zoom); var map3 = L.map('l-map3', { zoomControl: false, attributionControl: false }).setView(center, zoom); maps = [map1, map2, map3]; // The elements will be available to transform Maptastic('l-map1'); Maptastic('l-map2'); Maptastic('l-map3'); L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>', id: 'osm' }).addTo(map1); L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { maxZoom: 18, attribution: '&copy; <a href="http://www.esri.com/">Esri</a>, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community', id: 'esri-satellite' }).addTo(map2); L.tileLayer('//stamen-tiles-a.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '<a id="home-link" target="_top" href="../">Map tiles</a> by <a target="_top" href="http://stamen.com">Stamen Design</a>, under <a target="_top" href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a target="_top" href="http://openstreetmap.org">OpenStreetMap</a>, under <a target="_top" href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>. | Video from <a target="_top" href="http://mazwai.com/">Mazwai</a>.', id: 'stamen-toner' }).addTo(map3); // Firebase event listners myFirebaseRef.child('map/center').on('value', function(snapshot) { center = snapshot.val(); console.log(maps); $.each(maps, function(i, map) { map.setView(center, zoom); }); }); myFirebaseRef.child('map/zoom').on('value', function(snapshot) { zoom = snapshot.val(); $.each(maps, function(i, map) { map.setView(center, zoom); }); }); myFirebaseRef.child('flash1').on('value', function(snapshot) { var flag = snapshot.val(); console.log(flag); if(flag === true) { console.log('flash1!'); $.each(maps, function(i, map) { map.eachLayer(function (layer) { layer.setOpacity(0); setTimeout(function() { layer.setOpacity(1); }, 100); }); }); } }); myFirebaseRef.child('flash2').on('value', function(snapshot) { var flag = snapshot.val(); console.log(flag); if(flag === true) { console.log('flash2!'); $.each(maps, function(i, map) { map.eachLayer(function (layer) { setTimeout(function() { layer.setOpacity(0); setTimeout(function() { layer.setOpacity(1); }, 100); }, 100 * i); }); }); } }); myFirebaseRef.child('dataUrl').on('value', function(snapshot) { var url = snapshot.val(); console.log(url); createGeoJSONLayer(url); }); } initMap();
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getIterator2 = require('babel-runtime/core-js/get-iterator'); var _getIterator3 = _interopRequireDefault(_getIterator2); var _weakMap = require('babel-runtime/core-js/weak-map'); var _weakMap2 = _interopRequireDefault(_weakMap); var _lodash = require('lodash'); var _recursiveIterator = require('recursive-iterator'); var _recursiveIterator2 = _interopRequireDefault(_recursiveIterator); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * @function * @name ConfigTransform * @param {Config} config * @returns {Config|Object} */ /** * @typedef {Object|ConfigTransform} ConfigOptions */ /** * @private * @type {WeakMap} */ const STRING_RESOLVER = new _weakMap2.default(); /** * @class */ class ConfigOptionsResolver { /** * @constructor * @param {ConfigStringResolver} stringResolver */ constructor(stringResolver) { STRING_RESOLVER.set(this, stringResolver); } /** * @readonly * @type {ConfigStringResolver} */ get stringResolver() { return STRING_RESOLVER.get(this); } /** * @private * @param {Config} config * @param {ConfigOptions} options * @returns {Object} */ static valueOf(config, options) { return (0, _lodash.isFunction)(options) ? options.call(config, config) : options; } /** * @param {Config} config * @param {ConfigOptions} options * @returns {Object} */ resolve(config, options) { const value = ConfigOptionsResolver.valueOf(config, options); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(new _recursiveIterator2.default(value, 1, true)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { const _ref = _step.value; const parent = _ref.parent; const node = _ref.node; const key = _ref.key; if ((0, _lodash.isString)(node)) { parent[key] = this.stringResolver.resolve(node); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return value; } } exports.default = ConfigOptionsResolver; //# sourceMappingURL=ConfigOptionsResolver.js.map
const values = [ { "userEnteredValue": { "stringValue": "์ œ๋ชฉ" }, }, { "userEnteredValue": { "stringValue": "๋‚ด์šฉ" }, }, { "userEnteredValue": { "stringValue": "ํ™”๋ฉด์•„์ด๋””" }, }, { "userEnteredValue": { "stringValue": "ํ™”๋ฉด๋ช…" }, }, { "userEnteredValue": { "stringValue": "์ž‘์„ฑ์ž" }, }, { "userEnteredValue": { "stringValue": "์—ฐ๋ฝ์ฒ˜" }, }, { "userEnteredValue": { "stringValue": "๋“ฑ๋ก์ผ์‹œ" }, }, { "userEnteredValue": { "stringValue": "์ด๋ฏธ์ง€" }, }, { "userEnteredValue": { "stringValue": "os์ข…๋ฅ˜" }, }, { "userEnteredValue": { "stringValue": "os๋ฒ„์ „" }, }, { "userEnteredValue": { "stringValue": "๋””๋ฐ”์ด์Šค๋ช…" }, }, { "userEnteredValue": { "stringValue": "๋””๋ฐ”์ด์Šค์ •๋ณด" }, }, { "userEnteredValue": { "stringValue": "์ƒํƒœ" }, }, { "userEnteredValue": { "stringValue": "๋‹ด๋‹น์ž" }, }, ] const data = [ { "rowData": [ { values } ] } ] const SHEET_OPTIONS = { resource: { "properties": { "title": "issue_management" }, "sheets": [ { "properties": { "sheetId": 1, "title": "issue", }, data } ] } } const SCOPES = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive', ]; const CONF_BASE = __dirname + '/.conf' const OAUTH_OTKEN_PATH = CONF_BASE + '/sheets.googleapis.com-nodejs-quickstart.json' const CLIENT_SECRET = CONF_BASE + '/client_secret.json' const SHEET_FILEINFO = CONF_BASE + '/sheetFileInfo.json' module.exports = { SHEET_OPTIONS, SCOPES, OAUTH_OTKEN_PATH, CLIENT_SECRET, SHEET_FILEINFO }
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.17-2-13 description: > Array.prototype.some - 'length' is inherited accessor property without a get function on an Array-like object includes: [runTestCase.js] ---*/ function testcase() { var accessed = false; function callbackfn(val, idx, obj) { accessed = true; return val > 10; } var proto = {}; Object.defineProperty(proto, "length", { set: function () { }, configurable: true }); var Con = function () { }; Con.prototype = proto; var child = new Con(); child[0] = 11; child[1] = 12; return !Array.prototype.some.call(child, callbackfn) && !accessed; } runTestCase(testcase);
// This file is intended to be run with node.js, used by travis ci. var mocha = require("mocha"), expect = require("expect.js"), jQuery = require("jquery"); GLOBAL.jQuery = jQuery; GLOBAL.expect = expect; require("./unspamify.js"); require("./test/test.unspamify.js");
// Hmmm, IIRC objects are unordered. However, at least Chrome and Firefox fetch things in // the reverse order than specified here. Therefore e.g. Tracker appears at the top of // row of the tree view and CSC at the bottom. Which is what we want. ispy.detector_description = { "RPCMinusEndcap3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Resistive Plate Chambers (-)", fn: ispy.makeRPC, style: {color: "rgb(60%, 80%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "RPCPlusEndcap3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Resistive Plate Chambers (+)", fn: ispy.makeRPC, style: {color: "rgb(60%, 80%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "RPCBarrel3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Resistive Plate Chambers (barrel)", fn: ispy.makeRPC, style: {color: "rgb(60%, 80%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "GEMMinus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Gas Electron Multipliers (-)", fn: ispy.makeGEM, style: {color: "rgb(30%, 70%, 10%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "GEMPlus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Gas Electron Multipliers (+)", fn: ispy.makeGEM, style: {color: "rgb(30%, 70%, 10%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "GEMRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "Gas Electron Multipliers RZ", fn: ispy.makeGEM, style: {color: "rgb(30%, 70%, 10%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "CSC3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Cathode Strip Chambers", fn: ispy.makeCSC, style: {color: "rgb(60%, 70%, 10%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "CSCRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "Cathode Strip Chambers RZ", fn: ispy.makeCSC, style: {color: "rgb(60%, 70%, 10%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "DTs3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Drift Tubes", fn: ispy.makeDT, style: {color: "rgb(80%, 40%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "DTsRPhi_V1": { type: ispy.BOX, on: true, group: "Detector", name: "Drift Tubes RPhi", fn: ispy.makeDT, style: {color: "rgb(80%, 40%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: true, rhoz: false }, "DTsRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "Drift Tubes RZ", fn: ispy.makeDT, style: {color: "rgb(80%, 40%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "HcalForwardMinus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "HCAL Forward (-)", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "HcalForwardPlus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "HCAL Forward (+)", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "HcalForwardRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "HCAL Forward RZ", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "HcalOuter3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "HCAL Outer", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "HcalOuterRPhi_V1": { type: ispy.BOX, on: true, group: "Detector", name: "HCAL Outer RPhi", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: true, rhoz: false }, "HcalOuterRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "HCAL Outer RZ", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "HcalEndcapMinus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "HCAL Endcap (-)", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "HcalEndcapPlus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "HCAL Endcap (+)", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "HcalEndcapRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "HCAL Endcap RZ", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "HcalBarrel3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "HCAL Barrel", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "HcalBarrelRPhi_V1": { type: ispy.BOX, on: true, group: "Detector", name: "HCAL Barrel RPhi", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: true, rhoz: false }, "HcalBarrelRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "HCAL Barrel RZ", fn: ispy.makeHcal, style: {color: "rgb(70%, 70%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "EcalEndcapMinus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "ECAL Endcap (-)", fn: ispy.makeEcal, style: {color: "rgb(50%, 80%, 100%)", opacity: 0.1, linewidth: 0.5}, threed: true, rphi: false, rhoz: false }, "EcalEndcapPlus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "ECAL Endcap (+)", fn: ispy.makeEcal, style: {color: "rgb(50%, 80%, 100%)", opacity: 0.1, linewidth: 0.5}, threed: true, rphi: false, rhoz: false }, "EcalEndcapRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "ECAL Endcap RZ", fn: ispy.makeEcal, style: {color: "rgb(50%, 80%, 100%)", opacity: 0.75, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "EcalBarrel3D_V1": { type: ispy.BOX, on: true, group: "Detector", name: "ECAL Barrel", fn: ispy.makeEcal, style: {color: "rgb(50%, 80%, 100%)", opacity: 0.01, linewidth: 0.5}, threed: true, rphi: false, rhoz: false }, "EcalBarrelRPhi_V1": { type: ispy.BOX, on: true, group: "Detector", name: "ECAL Barrel RPhi", fn: ispy.makeEcal, style: {color: "rgb(50%, 80%, 100%)", opacity: 0.75, linewidth: 1.0}, threed: false, rphi: true, rhoz: false }, "EcalBarrelRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name: "ECAL Barrel RZ", fn: ispy.makeEcal, style: {color: "rgb(50%, 80%, 100%)", opacity: 0.75, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "TrackerRPhi_V1": { type: ispy.BOX, on: true, group: "Detector", name:"Tracker RPhi", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: true, rhoz: false }, "TrackerRZ_V1": { type: ispy.BOX, on: true, group: "Detector", name:"Tracker RZ", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: false, rphi: false, rhoz: true }, "SiStripTECMinus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Tracker Endcap (-)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "SiStripTECPlus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Tracker Endcap (+)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "SiStripTIDMinus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Tracker Inner Detector (-)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "SiStripTIDPlus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Tracker Inner Detector (+)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "SiStripTOB3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Tracker Outer Barrel", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "SiStripTIB3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Tracker Inner Barrel", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "PixelEndcapMinus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Pixel Endcap (-)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "PixelEndcapPlus3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Pixel Endcap (+)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "PixelBarrel3D_V1": { type: ispy.BOX, on: false, group: "Detector", name: "Pixel Barrel", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "PixelEndcapMinus3D_V2": { type: ispy.BOX, on: false, group: "Detector", name: "Pixel Endcap (-)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "PixelEndcapPlus3D_V2": { type: ispy.BOX, on: false, group: "Detector", name: "Pixel Endcap (+)", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false }, "PixelBarrel3D_V2": { type: ispy.BOX, on: false, group: "Detector", name: "Pixel Barrel", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 1.0}, threed: true, rphi: false, rhoz: false } }; ispy.event_description = { "SuperClusters_V1": { type: ispy.ASSOC, on: false, group: "ECAL", name: "SuperClusters", extra: "RecHitFractions_V1", assoc: "SuperClusterRecHitFractions_V1", fn: ispy.makeCaloClusters, style: {color: "rgb(100%, 20%, 0%)", opacity: 1.0} }, "EEDigis_V1": { type: ispy.SCALEDSOLIDTOWER, on: false, group: "ECAL", name: "Endcap Digis", fn: ispy.makeEcalDigi, style: {color: "rgb(100%, 20%, 0%)", opacity: 0.5, linewidth: 0.5}, scale: 1.0, selection: {"min_energy": 0.5} }, "EBDigis_V1": { type: ispy.SCALEDSOLIDTOWER, on: false, group: "ECAL", name: "Barrel Digis", fn: ispy.makeEcalDigi, style: {color: "rgb(100%, 20%, 0%)", opacity: 0.5, linewidth: 0.5}, scale: 1.0, selection: {"min_energy": 0.25} }, "EERecHits_V2": { type: ispy.SCALEDSOLIDTOWER, on: true, group: "ECAL", name: "Endcap Rec. Hits", fn: ispy.makeERecHit_V2, style: {color: "rgb(10%, 100%, 10%)", opacity: 0.5, linewidth: 0.5}, scale: 0.01, selection: {"min_energy": 0.5} }, "ESRecHits_V2": { type: ispy.SCALEDSOLIDTOWER, on: false, group: "ECAL", name: "Preshower Rec. Hits", fn: ispy.makeERecHit_V2, style: {color: "rgb(100%, 60%, 0%)", opacity: 0.5, linewidth: 0.5}, scale: 100.0, selection: {"min_energy": 0.0005} }, "EBRecHits_V2": { type: ispy.SCALEDSOLIDTOWER, on: true, group: "ECAL", name: "Barrel Rec. Hits", fn: ispy.makeERecHit_V2, style: {color: "rgb(10%, 100%, 10%)", opacity: 0.5, linewidth: 0.5}, scale: 0.1, selection: {"min_energy": 0.25} }, "HGCEERecHits_V1": { type: ispy.SCALEDSOLIDBOX, on: true, group: "ECAL", name: "HGC EE Rec. Hits", fn: ispy.makeHGCRecHit, style: {color: "rgb(10%, 100%, 10%)", opacity: 0.5, linewidth: 0.25}, selection: {"min_energy": 0.01} }, "HFRecHits_V2": { type: ispy.SCALEDSOLIDBOX, on: false, group: "HCAL", name: "Forward Rec. Hits", fn: ispy.makeHRecHit_V2, style: {color: "rgb(60%, 100%, 100%)", opacity: 0.5, linewidth: 0.25}, selection: {"min_energy": 0.0} }, "HORecHits_V2": { type: ispy.SCALEDSOLIDBOX, on: false, group: "HCAL", name: "Outer Rec. Hits", fn: ispy.makeHRecHit_V2, style: {color: "rgb(20%, 70%, 100%)", opacity: 0.5, linewidth: 0.25}, selection: {"min_energy": 1.0} }, "HERecHits_V2": { type: ispy.SCALEDSOLIDBOX, on: true, group: "HCAL", name: "Endcap Rec. Hits", fn: ispy.makeHRecHit_V2, style: {color: "rgb(20%, 70%, 100%)", opacity: 0.5, linewidth: 0.25}, selection: {"min_energy": 0.0} }, "HBRecHits_V2": { type: ispy.SCALEDSOLIDBOX, on: true, group: "HCAL", name: "Barrel Rec. Hits", fn: ispy.makeHRecHit_V2, style: {color: "rgb(20%, 70%, 100%)", opacity: 0.5, linewidth: 0.25}, selection: {"min_energy": 0.0} }, "HGCHEBRecHits_V1": { type: ispy.SCALEDSOLIDBOX, on: true, group: "HCAL", name: "HGC HE Back Rec. Hits", fn: ispy.makeHGCRecHit, style: {color: "rgb(20%, 70%, 100%)", opacity: 0.5, linewidth: 0.25}, selection: {"min_energy": 0.01} }, "HGCHEFRecHits_V1": { type: ispy.SCALEDSOLIDBOX, on: true, group: "HCAL", name: "HGC HE Front Rec. Hits", fn: ispy.makeHGCRecHit, style: {color: "rgb(20%, 70%, 100%)", opacity: 0.5, linewidth: 0.25}, selection: {"min_energy": 0.01} }, "Tracks_V1": { type: ispy.ASSOC, on: true, group: "Tracking", name: "Tracks (reco.)", extra: "Extras_V1", assoc: "TrackExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, lineCaps: "square", linewidth: 1}, selection: {"min_pt": 1.0, index: 2} }, "Tracks_V2": { type: ispy.ASSOC, on: true, group: "Tracking", name: "Tracks (reco.)", extra: "Extras_V1", assoc: "TrackExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, lineCaps: "square", linewidth: 1}, selection: {"min_pt": 1.0, "index": 2} }, "Tracks_V3": { type: ispy.ASSOC, on: true, group: "Tracking", name: "Tracks (reco.)", extra: "Extras_V1", assoc: "TrackExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, lineCaps: "square", linewidth: 1}, selection: {"min_pt": 1.0, "index": 2} }, "Tracks_V4": { type: ispy.ASSOC, on: true, group: "Tracking", name: "Tracks (reco.)", extra: "Extras_V1", assoc: "TrackExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, lineCaps: "square", linewidth: 1}, selection: {"min_pt": 1.0, "index": 2} }, "TrackDets_V1": { type: ispy.BOX, on: false, group: "Tracking", name: "Matching Tracker Dets", fn: ispy.makeTrackerPiece, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.5, linewidth: 0.5} }, "TrackingRecHits_V1": { type:ispy.POINT, on:false, group:"Tracking", name: "Tracking Rec Hits", fn:ispy.makeTrackingRecHits, style: {color: "rgb(100%, 100%, 0%)", size: 0.05} }, "SiStripClusters_V1": { type: ispy.POINT, on:false, group:"Tracking", name: "Si Strip Clusters", fn: ispy.makeTrackingClusters, style:{color: "rgb(80%, 20%, 0%)", size: 0.05} }, "SiPixelClusters_V1": { type: ispy.POINT, on:false, group:"Tracking", name: "Si Pixel Clusters", fn: ispy.makeTrackingClusters, style:{color: "rgb(100%, 40%, 0%)", size: 0.05} }, "Event_V1":{ type: ispy.TEXT, on: true, group: "Provenance", name: "Event", fn: ispy.makeEvent, style: {} }, "Event_V2":{ type: ispy.TEXT, on: true, group: "Provenance", name: "Event", fn: ispy.makeEvent, style: {} }, "Event_V3":{ type: ispy.TEXT, on: true, group: "Provenance", name: "Event", fn: ispy.makeEvent, style: {} }, "DTRecHits_V1": { type: ispy.SOLIDBOX, on: false, group: "Muon", name: "DT Rec. Hits", fn: ispy.makeDTRecHits, style: {color: "rgb(0%, 100%, 0%)", opacity: 0.5, linewidth: 1} }, "DTRecSegment4D_V1": { type: ispy.LINE, on: true, group: "Muon", name: "DT Rec. Segments (4D)", fn: ispy.makeDTRecSegments, style: {color: "rgb(100%, 100%, 0%)", opacity: 1.0, linewidth: 1.5} }, "RPCRecHits_V1": { type: ispy.LINE, on: true, group: "Muon", name: "RPC Rec. Hits", fn: ispy.makeRPCRecHits, style: {color: "rgb(80%, 100%, 0%)", opacity: 1.0, linewidth: 1.5} }, "MatchingGEMs_V1": { type: ispy.SOLIDBOX, on: true, group: "Muon", name: "Matching GEMs", fn: ispy.makeMuonChamber, style: {color: "rgb(100%,0%,10%)", opacity: 0.1, linewidth: 1} }, "GEMDigis_V2": { type: ispy.LINE, on: true, group: "Muon", name: "GEM Strip Digis", fn: ispy.makeGEMDigis_V2, style: {color: "rgb(100%, 10%, 100%)", opacity: 0.8, linewidth: 1} }, "GEMRecHits_V2": { type: ispy.LINE, on: true, group: "Muon", name: "GEM Rec. Hits (2D)", fn: ispy.makeGEMRecHits_V2, style: {color: "rgb(60%, 100%, 70%)", opacity: 1.0, linewidth: 1} }, "GEMSegments_V1": { type: ispy.LINE, on: true, group: "Muon", name: "GEM Segments", fn: ispy.makeGEMSegments_V2, style: {color: "rgb(100%, 70%, 100%)", opacity: 1.0, linewidth: 1} }, "GEMSegments_V2": { type: ispy.LINE, on: true, group: "Muon", name: "GEM Segments", fn: ispy.makeGEMSegments_V2, style: {color: "rgb(100%, 70%, 100%)", opacity: 1.0, linewidth: 1} }, "GEMSegments_V3": { type: ispy.LINE, on: true, group: "Muon", name: "GEM Segments", fn: ispy.makeGEMSegments_V2, style: {color: "rgb(100%, 70%, 100%)", opacity: 1.0, linewidth: 1} }, "CSCStripDigis_V1": { type: ispy.SOLIDBOX, on: false, group: "Muon", name: "CSC Strip Digis", fn: ispy.makeCSCStripDigis, style: {color: "rgb(100%, 20%, 100%)", opacity: 0.5, linewidth: 1} }, "CSCWireDigis_V1": { type: ispy.SOLIDBOX, on: false, group: "Muon", name: "CSC Wire Digis", fn: ispy.makeCSCWireDigis, style: {color: "rgb(100%, 60%, 100%)", opacity: 0.5, linewidth: 1} }, "CSCStripDigis_V2": { type: ispy.LINE, on: false, group: "Muon", name: "CSC Strip Digis", fn: ispy.makeCSCDigis_V2, style: {color: "rgb(100%, 20%, 100%)", opacity: 0.8, linewidth: 1} }, "CSCWireDigis_V2": { type: ispy.LINE, on: false, group: "Muon", name: "CSC Wire Digis", fn: ispy.makeCSCDigis_V2, style: {color: "rgb(100%, 60%, 100%)", opacity: 0.5, linewidth: 1} }, "CSCLCTDigis_V1": { type: ispy.POINT, on: false, group: "Muon", name: "CSC LCT Digis", fn: ispy.makeCSCLCTDigis, style: {color: "rgb(0%, 100%, 100%)", size: 0.15} }, "CSCCorrelatedLCTDigis_V2": { type: ispy.LINE, on: false, group: "Muon", name: "CSC Correlated LCT Digis", fn: ispy.makeCSCLCTCorrelatedLCTDigis, style: {color: "rgb(0%,100%,100%)", opacity:0.8, linewidth: 2} }, "MatchingCSCs_V1": { type: ispy.SOLIDBOX, on: true, group: "Muon", name: "Matching CSCs", fn: ispy.makeMuonChamber, style: {color: "rgb(100%,0%,0%)", opacity: 0.1, linewidth: 1} }, "CSCRecHit2Ds_V2": { type: ispy.LINE, on: true, group: "Muon", name: "CSC Rec. Hits (2D)", fn: ispy.makeCSCRecHit2Ds_V2, style: {color: "rgb(60%, 100%, 90%)", opacity: 1.0, linewidth: 1} }, "CSCSegments_V1": { type: ispy.LINE, on: true, group: "Muon", name: "CSC Segments", fn: ispy.makeCSCSegments, style: {color: "rgb(100%, 60%, 100%)", opacity: 1.0, linewidth: 1.5} }, "CSCSegments_V2": { type: ispy.LINE, on: true, group: "Muon", name: "CSC Segments", fn: ispy.makeCSCSegments, style: {color: "rgb(100%, 60%, 100%)", opacity: 1.0, linewidth: 1.5} }, "CSCSegments_V3": { type: ispy.LINE, on: true, group: "Muon", name: "CSC Segments", fn: ispy.makeCSCSegments, style: {color: "rgb(100%, 60%, 100%)", opacity: 1.0, linewidth: 1.5} }, "MuonChambers_V1": { type: ispy.SOLIDBOX, on: true, group: "Muon", name: "Matching muon chambers", fn: ispy.makeMuonChamber, style: {color: "rgb(100%, 0%, 0%)", opacity: 0.1, linewidth: 1} }, "CaloTowers_V2":{ type: ispy.STACKEDTOWER, on: false, group: "Physics", name: "Calo Towers", fn: ispy.makeCaloTower, style: {ecolor: "rgb(100%, 0%, 0%)", hcolor: "rgb(0%, 0%, 100%)", opacity: 0.5, linewidth: 1.0}, scale: 0.1, selection: {"min_energy": 0.1} }, "METs_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Missing Et (Reco)", fn: ispy.makeMET, style: {color: "rgb(100%, 50%, 100%)", linewidth:2, scale: 0.025}, selection: {"min_pt": 0.0} }, "PFMETs_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Missing Et (PF)", fn: ispy.makeMET, style: {color: "rgb(100%, 50%, 100%)", linewidth:2, scale: 0.025}, selection: {"min_pt": 0.0} }, "PATMETs_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Missing Et (PAT)", fn: ispy.makeMET, style: {color: "rgb(100%, 50%, 100%)", linewidth:2, scale: 0.025}, selection: {"min_pt": 0.0} }, "Jets_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Jets (Reco)", fn: ispy.makeJet, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.75}, selection: {"min_et": 10.0} }, "PFJets_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Jets (PF)", fn: ispy.makeJet, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.6}, selection: {"min_et": 10.0}, cuts: true }, "PFJets_V2": { type: ispy.SHAPE, on: false, group: "Physics", name: "Jets (PF)", fn: ispy.makeJetWithVertex, style: {color: "rgb(100%, 100%, 0%)", opacity: 0.6}, selection: {"min_et": 10.0}, cuts: true }, "GenJets_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Jets (Sim)", fn: ispy.makeJet, style: {color: "rgb(100%, 75%, 0%)", opacity: 0.8}, selection: {"min_et": 10.0} }, "PATJets_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Jets (PAT)", fn: ispy.makeJet, style: {color: "rgb(100%, 50%, 0%)", opacity: 0.3}, selection: {"min_et": 10.0} }, "Photons_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Photons (Reco)", fn: ispy.makePhoton, style: {color: "rgb(100%, 80%, 0%)", opacity: 1.0, linewidth: 3}, selection: {"min_energy": 10.0} }, "PATPhotons_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Photons (PAT)", fn: ispy.makePhoton, style: {color: "rgb(100%, 80%, 0%)", opacity: 1.0, linewidth: 3}, selection: {"min_energy":10.0} }, "GlobalMuons_V1": { type: ispy.ASSOC, on: true, group: "Physics", name: "Global Muons (Reco)", extra: "Points_V1", assoc: "MuonGlobalPoints_V1", fn: ispy.makeTrackPoints, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 3}, selection:{"min_pt":1.0, "index":0} }, "GlobalMuons_V2": { type: ispy.ASSOC, on: true, group: "Physics", name: "Global Muons (Reco)", extra: "Points_V1", assoc: "MuonGlobalPoints_V1", fn: ispy.makeTrackPoints, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 3}, selection:{"min_pt":1.0, "index":0} }, "PATGlobalMuons_V1": { type: ispy.ASSOC, on: true, group: "Physics", name: "Global Muons (PAT)", extra: "Points_V1", assoc: "PATMuonGlobalPoints_V1", fn: ispy.makeTrackPoints, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 3}, selection:{"min_pt":1.0, "index":0} }, "StandaloneMuons_V1": { type: ispy.ASSOC, on: false, group: "Physics", name: "Stand-alone Muons (Reco)", extra: "Points_V1", assoc: "MuonStandalonePoints_V1", fn: ispy.makeTrackPoints, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 3}, selection:{"min_pt":1.0, "index":0} }, "StandaloneMuons_V2": { type: ispy.ASSOC, on: false, group: "Physics", name: "Stand-alone Muons (Reco)", extra: "Extras_V1", assoc: "MuonTrackExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 1}, selection: {"min_pt":1.0, "index":0} }, "PATStandaloneMuons_V1": { type: ispy.ASSOC, on: false, group: "Physics", name: "Stand-alone Muons (PAT)", extra: "Extras_V1", assoc: "PATMuonTrackExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 1}, selection: {"min_pt":1.0, "index":0} }, "TrackerMuons_V1": { type: ispy.ASSOC, on: true, group: "Physics", name: "Tracker Muons (Reco)", extra: "Points_V1", assoc: "MuonTrackerPoints_V1", fn: ispy.makeTrackPoints, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 1}, selection:{"min_pt":1.0, "index":0} }, "TrackerMuons_V2": { type: ispy.ASSOC, on: true, group: "Physics", name: "Tracker Muons (Reco)", extra: "Extras_V1", assoc: "MuonTrackerExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 1}, selection:{"min_pt":1.0, "index":0} }, "PATTrackerMuons_V1": { type: ispy.ASSOC, on: true, group: "Physics", name: "Tracker Muons (PAT)", extra: "Points_V1", assoc: "PATMuonTrackerPoints_V1", fn: ispy.makeTrackPoints, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 1}, selection:{"min_pt":1.0, "index":0} }, "PATTrackerMuons_V2": { type: ispy.ASSOC, on: true, group: "Physics", name: "Tracker Muons (PAT)", extra: "Extras_V1", assoc: "PATMuonTrackExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(100%, 0%, 0%)", opacity: 1.0, linewidth: 1}, selection:{"min_pt":1.0, "index":0} }, "GsfElectrons_V1": { type: ispy.ASSOC, on: true, group: "Physics", name: "Electron Tracks (GSF)", extra: "Extras_V1", assoc: "GsfElectronExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(10%, 100%, 10%)", opacity: 0.9, linewidth: 3}, selection: {"min_pt":1.0, "index":0} }, "GsfElectrons_V2": { type: ispy.ASSOC, on: true, group: "Physics", name: "Electron Tracks (GSF)", extra: "Extras_V1", assoc: "GsfElectronExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(10%, 100%, 10%)", opacity: 1, linewidth: 3}, selection: {"min_pt":1.0, "index":0} }, "GsfElectrons_V3": { type: ispy.ASSOC, on: true, group: "Physics", name: "Electron Tracks (GSF)", extra: "Extras_V1", assoc: "GsfElectronExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(10%, 100%, 10%)", opacity: 1, linewidth: 3}, selection: {"min_pt":1.0, "index":0} }, "PATElectrons_V1": { type: ispy.ASSOC, on: true, group: "Physics", name: "Electron Tracks (PAT)", extra: "Extras_V1", assoc: "PATElectronExtras_V1", fn: ispy.makeTracks, style: {color: "rgb(10%, 100%, 10%)", opacity: 0.9, linewidth: 3}, selection: {"min_pt":1.0, "index":0} }, "ForwardProtons_V1": { type: ispy.SHAPE, on: false, group: "Physics", name: "Forward Protons", fn: ispy.makeProtons, style: {color: "rgb(10%, 10%, 100%)", opacity: 1.0}, selection: {} }, "Vertices_V1": { type:ispy.SHAPE, on:false, group:"Physics", name: "Vertices (Reco)", fn:ispy.makeVertex, style: {radius: 0.002, color: "rgb(100%, 100%, 0%)", opacity: 0.9} }, "PrimaryVertices_V1": { type:ispy.SHAPE, on:false, group:"Physics", name: "Primary Vertices (Reco)", fn:ispy.makeVertex, style: {radius: 0.002, color: "rgb(100%, 100%, 0%)", opacity: 1.0} }, "SecondaryVertices_V1": { type:ispy.SHAPE, on:false, group:"Physics", name: "Secondary Vertices (Reco)", fn:ispy.makeVertex, style: {radius: 0.002, color: "rgb(100%, 40%, 0%)", opacity: 1.0} }, "VertexCompositeCandidates_V1": { type:ispy.SHAPE, on:false, group:"Physics", name: "V0Vertices (Reco)", fn:ispy.makeVertexCompositeCandidate, style: {radius: 0.002, color: "rgb(100%, 0%, 0%)", opacity: 1.0} }, "SimVertices_V1": { type:ispy.SHAPE, on:false, group:"Physics", name: "Vertices (Sim)", fn:ispy.makeSimVertex, style: {color: "rgb(80%, 20%, 0%)", opacity: 0.9} } }; ispy.disabled = []; ispy.view3D = []; ispy.viewRPhi = []; ispy.viewRZ = []; for ( var key in ispy.detector_description ) { /* Not used (yet) if ( ispy.detector_description[key].threed ) ispy.view3D.push(key); if ( ispy.detector_description[key].rphi ) ispy.viewRPhi.push(key); if ( ispy.detector_description[key].rhoz ) ispy.viewRZ.push(key); */ if ( ! ispy.detector_description[key].on ) { ispy.disabled[key] = true; } } for ( var key in ispy.event_description ) { if ( ! ispy.event_description[key].on ) { ispy.disabled[key] = true; } } ispy.data_groups = [ "Provenance", "Tracking", "ECAL", "HCAL", "Muon", "Physics" ]; ispy.table_caption = '<caption>Click on a name under "Provenance", "Tracking", "ECAL", "HCAL", "Muon", and "Physics" to view contents in table</caption>';
var dir_e0921d6bc91030c0216d63eb1c6e43b7 = [ [ "TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs", "_win_forms_game_2obj_2_debug_2_temporary_generated_file__036_c0_b5_b-1481-4323-8_d20-8_f5_a_d_c_b23_d92_8cs.html", null ], [ "TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs", "_win_forms_game_2obj_2_debug_2_temporary_generated_file__5937a670-0e60-4077-877b-f7221da3dda1_8cs.html", null ], [ "TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs", "_win_forms_game_2obj_2_debug_2_temporary_generated_file___e7_a71_f73-0_f8_d-4_b9_b-_b56_e-8_e70_b10_b_c5_d3_8cs.html", null ] ];
'use strict'; function bsHasError(bsProcessValidator) { return { restrict: 'A', link: function (scope, element) { bsProcessValidator(scope, element, 'ng-invalid', 'has-error'); } }; } var app = angular.module('ip.bsHas'); app.directive('bsHasError', bsHasError);
// clear body document.body.innerHTML = ''; let observer = new MutationObserver( (mutationRecords) => console.log(mutationRecords)); // Create initial element document.body.appendChild(document.createElement('div')); // Observe the <body> subtree observer.observe(document.body, { attributes: true, subtree: true }); // Modify <body> subtree document.body.firstChild.setAttribute('foo', 'bar'); // Subtree modification registers as mutation // [ // { // addedNodes: NodeList[], // attributeName: "foo", // attributeNamespace: null, // oldValue: null, // nextSibling: null, // previousSibling: null, // removedNodes: NodeList[], // target: div, // type: "attributes", // } // ] SubtreeMutationExample01.js
๏ปฟangular.module("clientApp.modelsModule") .factory("Log", [ function() { function Log(itemId) { var that = this, _id = null, _itemId = itemId, _dateTimeOverride, _controlLogs = []; that.addControlLog = function(controlId, controlOptionId, value) { _controlLogs.push({ controlId: controlId, controlOptionId: controlOptionId, value: value }); } that.isNew = function() { return _id === null; } that.setDateTimeOverride = function(date) { _dateTimeOverride = date; } that.toDto = function() { var dto = { itemId: _itemId, controlLogs: _controlLogs } if (_dateTimeOverride) { dto.dateTimeOverride = _dateTimeOverride; } return dto; } } return Log; } ]);
var color_8hpp = [ [ "color", "d9/def/classstd_1_1math_1_1color.html", "d9/def/classstd_1_1math_1_1color" ], [ "color", "d9/def/classstd_1_1math_1_1color.html", "d9/def/classstd_1_1math_1_1color" ], [ "cold", "d6/dfd/color_8hpp.html#a8e4673c88cd9920884053799fdd5c583", null ], [ "colf", "d6/dfd/color_8hpp.html#a14b1452193e096079256021cbff6e4ec", null ], [ "_max", "d6/dfd/color_8hpp.html#a5ee39c505dd91b953c598cf384f9e313", null ], [ "_min", "d6/dfd/color_8hpp.html#a8ae6184cee42b608ef0527120991b302", null ], [ "brightness", "d6/dfd/color_8hpp.html#ac0a348524105b3fe36d161084e73b243", null ], [ "from_cmy", "d6/dfd/color_8hpp.html#a66a49b2de8cf724aa07d1262f6eb4621", null ], [ "from_hsv", "d6/dfd/color_8hpp.html#a3dd1dc1f5379113655d2f6e07ef25411", null ], [ "from_yuv", "d6/dfd/color_8hpp.html#af97c61b0f790faa9969251e7739a71b2", null ], [ "interpolate", "d6/dfd/color_8hpp.html#adb1f279941b8942d6c3aab970eb51e33", null ], [ "negate", "d6/dfd/color_8hpp.html#a5f3d2bf8fa13a829b2c692a30357091c", null ], [ "operator!=", "d6/dfd/color_8hpp.html#a637cee37599143b7be496217678a3612", null ], [ "operator*", "d6/dfd/color_8hpp.html#af272014535fe1ad7c2de459af9e272c5", null ], [ "operator*", "d6/dfd/color_8hpp.html#a0ed2671f41beb1cab464061d0bbc30bb", null ], [ "operator*", "d6/dfd/color_8hpp.html#a8bfcc82534192c688d7ce6c3a94fa327", null ], [ "operator+", "d6/dfd/color_8hpp.html#a0027afbf52c17a2199c774d666b69973", null ], [ "operator-", "d6/dfd/color_8hpp.html#a60940ab449d09c34ede75d29595b3a9a", null ], [ "operator-", "d6/dfd/color_8hpp.html#ab96b943b255e7cec4e8b256693467d31", null ], [ "operator/", "d6/dfd/color_8hpp.html#a6c3412e54fcbfc115837107294936997", null ], [ "operator/", "d6/dfd/color_8hpp.html#a8d443d706d40e0342d8b96dc450b399b", null ], [ "operator==", "d6/dfd/color_8hpp.html#aa70d078967b672dc4967e7c358f9ed67", null ] ];
var crypto = require("crypto"); var generateDBID = function(){ return crypto.randomBytes(10).toString('hex'); } module.exports.init = function(data){ try{ var timeStamp = String(1*new Date()), id = generateDBID()+"_"+timeStamp; var d = { "TableName":"graphshape", "Item":{ "txid":{ "S":id } }, } for(var i in data){ for(var j in data[i]){ if(typeof data[i][j] == "object"){ d["Item"][j] = {"S":JSON.stringify(data[i][j])} }else if(typeof data[i][j] != "function"){ d["Item"][j] = {"S":String(data[i][j])} } } } return d; }catch(er){console.log(er.message);} }
'use strict'; class LoginController { constructor(Auth, $state) { this.user = {}; this.errors = {}; this.submitted = false; this.Auth = Auth; this.$state = $state; } login(form) { this.submitted = true; if (form.$valid) { this.Auth.login({ email: this.user.email, password: this.user.password }) .then(() => { // Logged in, redirect to home this.$state.go('main'); }) .catch(err => { this.errors.other = err.message; }); } } } angular.module('swedicApp') .controller('LoginController', LoginController);
$(document).ready(function() { // Helper function to guarantee cross-browser compatibility // adapted from: http://stackoverflow.com/a/16157942 function localeString(x, sep, grp) { var sx = ('' + x).split('.'), s = '', i, j; sep || (sep = ','); // default separator grp || grp === 0 || (grp = 3); // default grouping i = sx[0].length; while (i > grp) { j = i - grp; s = sep + sx[0].slice(j, i) + s; i = j; } s = sx[0].slice(0, i) + s; sx[0] = s; return sx.join('.'); } // To change portfolioValue's input field (lose arrows and other functionality) $('#portfolioValue')[0].type = 'text'; // To format the number when the app starts up $('#portfolioValue').val(localeString($('#portfolioValue').val())); // To format the number whenever the input changes $('#portfolioValue').keyup(function(event) { $(this).val(localeString($(this).val().replace(/,/g, ''))); }); });
'use strict'; module.exports = require('skyer-mongo-client-component');
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: '\n;\n' }, dist: { src: [ 'bower_components/jquery/jquery.min.js', 'bower_components/jquery.transit/jquery.transit.js', 'private/js/*.js' ], dest: 'public/js/<%= pkg.name %>.js' } }, less: { development: { options: { cleancss: false, compress: false, }, files: { 'public/css/hovertest.css': 'private/less/hovertest.less' } } }, watch: { less: { files: 'private/less/*.less', tasks: [ 'css-dev' ] }, js: { files: [ 'private/js/*.js' ], tasks: [ 'js-dev' ] } } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['js-dev', 'css-dev', 'watch']); grunt.registerTask('js-dev', ['concat']); grunt.registerTask('css-dev', ['less:development']); };
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports, __webpack_require__) { __webpack_require__(301); module.exports = __webpack_require__(301); /***/ }), /***/ 301: /***/ (function(module, exports) { (function( window, undefined ) { kendo.cultures["qut-GT"] = { name: "qut-GT", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { name: "Guatemalan Quetzal", abbr: "GTQ", pattern: ["($n)","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "Q" } }, calendars: { standard: { days: { names: ["juq\u0027ij","kaq\u0027ij","oxq\u0027ij","kajq\u0027ij","joq\u0027ij","waqq\u0027ij","wuqq\u0027ij"], namesAbbr: ["juq\u0027","kaq\u0027","oxq\u0027","kajq\u0027","joq\u0027","waqq\u0027","wuqq\u0027"], namesShort: ["ju","ka","ox","kj","jo","wa","wu"] }, months: { names: ["nab\u0027e ik\u0027","ukab\u0027 ik\u0027","urox ik\u0027","ukaj ik\u0027","uro ik\u0027","uwaq ik\u0027","uwuq ik\u0027","uwajxaq ik\u0027","ub\u0027elej ik\u0027","ulaj ik\u0027","ujulaj ik\u0027","ukab\u0027laj ik\u0027"], namesAbbr: ["nab\u0027e","ukab\u0027","urox","ukaj","uro","uwaq","uwuq","uwajxaq","ub\u0027elej","ulaj","ujulaj","ukab\u0027laj"] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "dd/MM/yyyy", D: "dddd, dd' rech 'MMMM' rech 'yyyy", F: "dddd, dd' rech 'MMMM' rech 'yyyy h:mm:ss tt", g: "dd/MM/yyyy h:mm tt", G: "dd/MM/yyyy h:mm:ss tt", m: "d' rech 'MMMM", M: "d' rech 'MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM' rech 'yyyy", Y: "MMMM' rech 'yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); /***/ }) /******/ });
var RuleStatement = require('./rule_statement'); function RuleExpression(a, b, operator) { var self = this; function aggregate(x, andMethod, orMethod) { if(x instanceof RuleExpression) { return x.aggregate(andMethod, orMethod); } else if(x instanceof RuleStatement) { return x.evaluate(); } else { throw new Error('a and b have to be an instance of RuleExpression or RuleStatement'); } } self.getB = function () { return b; }; /** * Aggregates all subconditions to a single degree of accomplishment * @param value * @returns {number} */ self.aggregate = function(andMethod, orMethod) { var resA = aggregate(a, andMethod, orMethod); var resB = aggregate(b, andMethod, orMethod); if(operator === 'and') { return andMethod(resA, resB); } else if (operator === 'or') { return orMethod(resA, resB) } }; } module.exports = RuleExpression;
Clazz.declarePackage ("JV"); Clazz.load (["javajs.api.BytePoster", "java.util.Hashtable"], "JV.FileManager", ["java.io.BufferedInputStream", "$.BufferedReader", "java.lang.Boolean", "java.net.URL", "$.URLEncoder", "java.util.Map", "JU.AU", "$.BArray", "$.Base64", "$.LimitedLineReader", "$.Lst", "$.OC", "$.PT", "$.Rdr", "$.SB", "J.api.Interface", "J.io.FileReader", "JS.SV", "JU.Logger", "JV.JC", "$.JmolAsyncException", "$.Viewer"], function () { c$ = Clazz.decorateAsClass (function () { this.vwr = null; this.spartanDoc = null; this.jzu = null; this.pathForAllFiles = ""; this.nameAsGiven = "zapped"; this.fullPathName = null; this.lastFullPathName = null; this.lastNameAsGiven = "zapped"; this.fileName = null; this.appletDocumentBaseURL = null; this.appletProxy = null; this.cache = null; this.pngjCache = null; this.spardirCache = null; Clazz.instantialize (this, arguments); }, JV, "FileManager", null, javajs.api.BytePoster); Clazz.prepareFields (c$, function () { this.cache = new java.util.Hashtable (); }); Clazz.makeConstructor (c$, function (vwr) { this.vwr = vwr; this.clear (); }, "JV.Viewer"); Clazz.defineMethod (c$, "spartanUtil", function () { return (this.spartanDoc == null ? this.spartanDoc = (J.api.Interface.getInterface ("J.adapter.readers.spartan.SpartanUtil", this.vwr, "fm getSpartanUtil()")).set (this) : this.spartanDoc); }); Clazz.defineMethod (c$, "getJzu", function () { return (this.jzu == null ? this.jzu = J.api.Interface.getOption ("io.JmolUtil", this.vwr, "file") : this.jzu); }); Clazz.defineMethod (c$, "clear", function () { this.setFileInfo ( Clazz.newArray (-1, [this.vwr.getZapName ()])); this.spardirCache = null; }); Clazz.defineMethod (c$, "setLoadState", function (htParams) { if (this.vwr.getPreserveState ()) { htParams.put ("loadState", this.vwr.g.getLoadState (htParams)); }}, "java.util.Map"); Clazz.defineMethod (c$, "getPathForAllFiles", function () { return this.pathForAllFiles; }); Clazz.defineMethod (c$, "setPathForAllFiles", function (value) { if (value.length > 0 && !value.endsWith ("/") && !value.endsWith ("|")) value += "/"; return this.pathForAllFiles = value; }, "~S"); Clazz.defineMethod (c$, "setFileInfo", function (fileInfo) { if (fileInfo == null) { this.fullPathName = this.lastFullPathName; this.nameAsGiven = this.lastNameAsGiven; return; }this.fullPathName = fileInfo[0]; this.fileName = fileInfo[Math.min (1, fileInfo.length - 1)]; this.nameAsGiven = fileInfo[Math.min (2, fileInfo.length - 1)]; if (!this.nameAsGiven.equals ("zapped")) { this.lastNameAsGiven = this.nameAsGiven; this.lastFullPathName = this.fullPathName; }}, "~A"); Clazz.defineMethod (c$, "getFileInfo", function () { return Clazz.newArray (-1, [this.fullPathName, this.fileName, this.nameAsGiven]); }); Clazz.defineMethod (c$, "getFullPathName", function (orPrevious) { var f = (this.fullPathName != null ? this.fullPathName : this.nameAsGiven); return (!orPrevious || !f.equals ("zapped") ? f : this.lastFullPathName != null ? this.lastFullPathName : this.lastNameAsGiven); }, "~B"); Clazz.defineMethod (c$, "getFileName", function () { return this.fileName != null ? this.fileName : this.nameAsGiven; }); Clazz.defineMethod (c$, "getAppletDocumentBase", function () { return (this.appletDocumentBaseURL == null ? "" : this.appletDocumentBaseURL.toString ()); }); Clazz.defineMethod (c$, "setAppletContext", function (documentBase) { try { System.out.println ("setting document base to \"" + documentBase + "\""); this.appletDocumentBaseURL = (documentBase.length == 0 ? null : new java.net.URL (Clazz.castNullAs ("java.net.URL"), documentBase, null)); } catch (e) { if (Clazz.exceptionOf (e, java.net.MalformedURLException)) { System.out.println ("error setting document base to " + documentBase); } else { throw e; } } }, "~S"); Clazz.defineMethod (c$, "setAppletProxy", function (appletProxy) { this.appletProxy = (appletProxy == null || appletProxy.length == 0 ? null : appletProxy); }, "~S"); Clazz.defineMethod (c$, "createAtomSetCollectionFromFile", function (name, htParams, isAppend) { if (htParams.get ("atomDataOnly") == null) this.setLoadState (htParams); var name0 = name; name = this.vwr.resolveDatabaseFormat (name); if (!name0.equals (name) && name0.indexOf ("/") < 0 && JV.Viewer.hasDatabasePrefix (name0)) { htParams.put ("dbName", name0); }if (name.endsWith ("%2D%")) { var filter = htParams.get ("filter"); htParams.put ("filter", (filter == null ? "" : filter) + "2D"); name = name.substring (0, name.length - 4); }var pt = name.indexOf ("::"); var nameAsGiven = (pt >= 0 ? name.substring (pt + 2) : name); var fileType = (pt >= 0 ? name.substring (0, pt) : null); JU.Logger.info ("\nFileManager.getAtomSetCollectionFromFile(" + nameAsGiven + ")" + (name.equals (nameAsGiven) ? "" : " //" + name)); var names = this.getClassifiedName (nameAsGiven, true); if (names.length == 1) return names[0]; var fullPathName = names[0]; var fileName = names[1]; htParams.put ("fullPathName", (fileType == null ? "" : fileType + "::") + JV.FileManager.fixDOSName (fullPathName)); if (this.vwr.getBoolean (603979880) && this.vwr.getBoolean (603979825)) this.vwr.getChimeMessenger ().update (fullPathName); var fileReader = new J.io.FileReader (this.vwr, fileName, fullPathName, nameAsGiven, fileType, null, htParams, isAppend); fileReader.run (); return fileReader.getAtomSetCollection (); }, "~S,java.util.Map,~B"); Clazz.defineMethod (c$, "createAtomSetCollectionFromFiles", function (fileNames, htParams, isAppend) { this.setLoadState (htParams); var fullPathNames = new Array (fileNames.length); var namesAsGiven = new Array (fileNames.length); var fileTypes = new Array (fileNames.length); for (var i = 0; i < fileNames.length; i++) { var pt = fileNames[i].indexOf ("::"); var nameAsGiven = (pt >= 0 ? fileNames[i].substring (pt + 2) : fileNames[i]); System.out.println (i + " FM " + nameAsGiven); var fileType = (pt >= 0 ? fileNames[i].substring (0, pt) : null); var names = this.getClassifiedName (nameAsGiven, true); if (names.length == 1) return names[0]; fullPathNames[i] = names[0]; fileNames[i] = JV.FileManager.fixDOSName (names[0]); fileTypes[i] = fileType; namesAsGiven[i] = nameAsGiven; } htParams.put ("fullPathNames", fullPathNames); htParams.put ("fileTypes", fileTypes); var filesReader = this.newFilesReader (fullPathNames, namesAsGiven, fileTypes, null, htParams, isAppend); filesReader.run (); return filesReader.getAtomSetCollection (); }, "~A,java.util.Map,~B"); Clazz.defineMethod (c$, "createAtomSetCollectionFromString", function (strModel, htParams, isAppend) { this.setLoadState (htParams); var isAddH = (strModel.indexOf ("Viewer.AddHydrogens") >= 0); var fnames = (isAddH ? this.getFileInfo () : null); var fileReader = new J.io.FileReader (this.vwr, "string", null, null, null, JU.Rdr.getBR (strModel), htParams, isAppend); fileReader.run (); if (fnames != null) this.setFileInfo (fnames); if (!isAppend && !(Clazz.instanceOf (fileReader.getAtomSetCollection (), String))) { this.setFileInfo ( Clazz.newArray (-1, [strModel === "5\n\nC 0 0 0\nH .63 .63 .63\nH -.63 -.63 .63\nH -.63 .63 -.63\nH .63 -.63 -.63" ? "Jmol Model Kit" : "string"])); }return fileReader.getAtomSetCollection (); }, "~S,java.util.Map,~B"); Clazz.defineMethod (c$, "createAtomSeCollectionFromStrings", function (arrayModels, loadScript, htParams, isAppend) { if (!htParams.containsKey ("isData")) { var oldSep = "\"" + this.vwr.getDataSeparator () + "\""; var tag = "\"" + (isAppend ? "append" : "model") + " inline\""; var sb = new JU.SB (); sb.append ("set dataSeparator \"~~~next file~~~\";\ndata ").append (tag); for (var i = 0; i < arrayModels.length; i++) { if (i > 0) sb.append ("~~~next file~~~"); sb.append (arrayModels[i]); } sb.append ("end ").append (tag).append (";set dataSeparator ").append (oldSep); loadScript.appendSB (sb); }this.setLoadState (htParams); JU.Logger.info ("FileManager.getAtomSetCollectionFromStrings(string[])"); var fullPathNames = new Array (arrayModels.length); var readers = new Array (arrayModels.length); for (var i = 0; i < arrayModels.length; i++) { fullPathNames[i] = "string[" + i + "]"; readers[i] = JV.FileManager.newDataReader (this.vwr, arrayModels[i]); } var filesReader = this.newFilesReader (fullPathNames, fullPathNames, null, readers, htParams, isAppend); filesReader.run (); return filesReader.getAtomSetCollection (); }, "~A,JU.SB,java.util.Map,~B"); Clazz.defineMethod (c$, "createAtomSeCollectionFromArrayData", function (arrayData, htParams, isAppend) { JU.Logger.info ("FileManager.getAtomSetCollectionFromArrayData(Vector)"); var nModels = arrayData.size (); var fullPathNames = new Array (nModels); var readers = new Array (nModels); for (var i = 0; i < nModels; i++) { fullPathNames[i] = "String[" + i + "]"; readers[i] = JV.FileManager.newDataReader (this.vwr, arrayData.get (i)); } var filesReader = this.newFilesReader (fullPathNames, fullPathNames, null, readers, htParams, isAppend); filesReader.run (); return filesReader.getAtomSetCollection (); }, "JU.Lst,java.util.Map,~B"); c$.newDataReader = Clazz.defineMethod (c$, "newDataReader", function (vwr, data) { var reader = (Clazz.instanceOf (data, String) ? "String" : JU.AU.isAS (data) ? "Array" : Clazz.instanceOf (data, JU.Lst) ? "List" : null); if (reader == null) return null; var dr = J.api.Interface.getInterface ("JU." + reader + "DataReader", vwr, "file"); return dr.setData (data); }, "JV.Viewer,~O"); Clazz.defineMethod (c$, "newFilesReader", function (fullPathNames, namesAsGiven, fileTypes, readers, htParams, isAppend) { var fr = J.api.Interface.getOption ("io.FilesReader", this.vwr, "file"); fr.set (this, this.vwr, fullPathNames, namesAsGiven, fileTypes, readers, htParams, isAppend); return fr; }, "~A,~A,~A,~A,java.util.Map,~B"); Clazz.defineMethod (c$, "createAtomSetCollectionFromDOM", function (DOMNode, htParams) { var aDOMReader = J.api.Interface.getOption ("io.DOMReadaer", this.vwr, "file"); aDOMReader.set (this, this.vwr, DOMNode, htParams); aDOMReader.run (); return aDOMReader.getAtomSetCollection (); }, "~O,java.util.Map"); Clazz.defineMethod (c$, "createAtomSetCollectionFromReader", function (fullPathName, name, reader, htParams) { var fileReader = new J.io.FileReader (this.vwr, name, fullPathName, null, null, reader, htParams, false); fileReader.run (); return fileReader.getAtomSetCollection (); }, "~S,~S,~O,java.util.Map"); Clazz.defineMethod (c$, "getBufferedInputStream", function (fullPathName) { var ret = this.getBufferedReaderOrErrorMessageFromName (fullPathName, new Array (2), true, true); return (Clazz.instanceOf (ret, java.io.BufferedInputStream) ? ret : null); }, "~S"); Clazz.defineMethod (c$, "getBufferedInputStreamOrErrorMessageFromName", function (name, fullName, showMsg, checkOnly, outputBytes, allowReader, allowCached) { var bis = null; var ret = null; var errorMessage = null; var cacheBytes = (allowCached && outputBytes == null ? cacheBytes = this.getPngjOrDroppedBytes (fullName, name) : null); try { if (allowCached && name.indexOf (".png") >= 0 && this.pngjCache == null && !this.vwr.getBoolean (603979960)) this.pngjCache = new java.util.Hashtable (); if (cacheBytes == null) { var isPngjBinaryPost = (name.indexOf ("?POST?_PNGJBIN_") >= 0); var isPngjPost = (isPngjBinaryPost || name.indexOf ("?POST?_PNGJ_") >= 0); if (name.indexOf ("?POST?_PNG_") > 0 || isPngjPost) { var errMsg = new Array (1); var bytes = this.vwr.getImageAsBytes (isPngjPost ? "PNGJ" : "PNG", 0, 0, -1, errMsg); if (errMsg[0] != null) return errMsg[0]; if (isPngjBinaryPost) { outputBytes = bytes; name = JU.PT.rep (name, "?_", "=_"); } else { name = new JU.SB ().append (name).append ("=").appendSB (JU.Base64.getBase64 (bytes)).toString (); }}var iurl = JU.OC.urlTypeIndex (name); var isURL = (iurl >= 0); var post = null; if (isURL && (iurl = name.indexOf ("?POST?")) >= 0) { post = name.substring (iurl + 6); name = name.substring (0, iurl); }var isApplet = (this.appletDocumentBaseURL != null); if (isApplet || isURL) { if (isApplet && isURL && this.appletProxy != null) name = this.appletProxy + "?url=" + this.urlEncode (name); var url = (isApplet ? new java.net.URL (this.appletDocumentBaseURL, name, null) : new java.net.URL (Clazz.castNullAs ("java.net.URL"), name, null)); if (checkOnly) return null; name = url.toString (); if (showMsg && name.toLowerCase ().indexOf ("password") < 0) JU.Logger.info ("FileManager opening url " + name); ret = this.vwr.apiPlatform.getURLContents (url, outputBytes, post, false); var bytes = null; if (Clazz.instanceOf (ret, JU.SB)) { var sb = ret; if (allowReader && !JU.Rdr.isBase64 (sb)) return JU.Rdr.getBR (sb.toString ()); bytes = JU.Rdr.getBytesFromSB (sb); } else if (JU.AU.isAB (ret)) { bytes = ret; }if (bytes != null) ret = JU.Rdr.getBIS (bytes); } else if (!allowCached || (cacheBytes = this.cacheGet (name, true)) == null) { if (showMsg) JU.Logger.info ("FileManager opening file " + name); ret = this.vwr.apiPlatform.getBufferedFileInputStream (name); }if (Clazz.instanceOf (ret, String)) return ret; }bis = (cacheBytes == null ? ret : JU.Rdr.getBIS (cacheBytes)); if (checkOnly) { bis.close (); bis = null; }return bis; } catch (e) { if (Clazz.exceptionOf (e, Exception)) { try { if (bis != null) bis.close (); } catch (e1) { if (Clazz.exceptionOf (e1, java.io.IOException)) { } else { throw e1; } } errorMessage = "" + e; } else { throw e; } } return errorMessage; }, "~S,~S,~B,~B,~A,~B,~B"); c$.getBufferedReaderForResource = Clazz.defineMethod (c$, "getBufferedReaderForResource", function (vwr, resourceClass, classPath, resourceName) { var url; { }resourceName = (url == null ? vwr.vwrOptions.get ("codePath") + classPath + resourceName : url.getFile ()); if (vwr.async) { var bytes = vwr.fm.cacheGet (resourceName, false); if (bytes == null) throw new JV.JmolAsyncException (resourceName); return JU.Rdr.getBufferedReader (JU.Rdr.getBIS (bytes), null); }return vwr.fm.getBufferedReaderOrErrorMessageFromName (resourceName, Clazz.newArray (-1, [null, null]), false, true); }, "JV.Viewer,~O,~S,~S"); Clazz.defineMethod (c$, "urlEncode", function (name) { try { return java.net.URLEncoder.encode (name, "utf-8"); } catch (e) { if (Clazz.exceptionOf (e, java.io.UnsupportedEncodingException)) { return name; } else { throw e; } } }, "~S"); Clazz.defineMethod (c$, "getEmbeddedFileState", function (fileName, allowCached, sptName) { var dir = this.getZipDirectory (fileName, false, allowCached); if (dir.length == 0) { var state = this.vwr.getFileAsString4 (fileName, -1, false, true, false, "file"); return (state.indexOf ("**** Jmol Embedded Script ****") < 0 ? "" : JV.FileManager.getEmbeddedScript (state)); }for (var i = 0; i < dir.length; i++) if (dir[i].indexOf (sptName) >= 0) { var data = Clazz.newArray (-1, [fileName + "|" + dir[i], null]); this.getFileDataAsString (data, -1, false, false, false); return data[1]; } return ""; }, "~S,~B,~S"); Clazz.defineMethod (c$, "getFullPathNameOrError", function (filename, getStream, ret) { var names = this.getClassifiedName (JV.JC.fixProtocol (filename), true); if (names == null || names[0] == null || names.length < 2) return Clazz.newArray (-1, [null, "cannot read file name: " + filename]); var name = names[0]; var fullPath = JV.FileManager.fixDOSName (names[0]); name = JU.Rdr.getZipRoot (name); var errMsg = this.getBufferedInputStreamOrErrorMessageFromName (name, fullPath, false, !getStream, null, false, !getStream); ret[0] = fullPath; if (Clazz.instanceOf (errMsg, String)) ret[1] = errMsg; return errMsg; }, "~S,~B,~A"); Clazz.defineMethod (c$, "getBufferedReaderOrErrorMessageFromName", function (name, fullPathNameReturn, isBinary, doSpecialLoad) { name = JV.JC.fixProtocol (name); var data = this.cacheGet (name, false); var isBytes = JU.AU.isAB (data); var bytes = (isBytes ? data : null); if (name.startsWith ("cache://")) { if (data == null) return "cannot read " + name; if (isBytes) { bytes = data; } else { return JU.Rdr.getBR (data); }}var names = this.getClassifiedName (name, true); if (names == null) return "cannot read file name: " + name; if (fullPathNameReturn != null) fullPathNameReturn[0] = JV.FileManager.fixDOSName (names[0]); return this.getUnzippedReaderOrStreamFromName (names[0], bytes, false, isBinary, false, doSpecialLoad, null); }, "~S,~A,~B,~B"); Clazz.defineMethod (c$, "getUnzippedReaderOrStreamFromName", function (name, bytesOrStream, allowZipStream, forceInputStream, isTypeCheckOnly, doSpecialLoad, htParams) { if (doSpecialLoad && bytesOrStream == null) { var o = (name.endsWith (".spt") ? Clazz.newArray (-1, [null, null, null]) : name.indexOf (".spardir") < 0 ? null : this.spartanUtil ().getFileList (name, isTypeCheckOnly)); if (o != null) return o; }name = JV.JC.fixProtocol (name); if (bytesOrStream == null && (bytesOrStream = this.getCachedPngjBytes (name)) != null && htParams != null) htParams.put ("sourcePNGJ", Boolean.TRUE); name = name.$replace ("#_DOCACHE_", ""); var fullName = name; var subFileList = null; if (name.indexOf ("|") >= 0) { subFileList = JU.PT.split (name.$replace ('\\', '/'), "|"); if (bytesOrStream == null) JU.Logger.info ("FileManager opening zip " + name); name = subFileList[0]; }var t = (bytesOrStream == null ? this.getBufferedInputStreamOrErrorMessageFromName (name, fullName, true, false, null, !forceInputStream, true) : JU.AU.isAB (bytesOrStream) ? JU.Rdr.getBIS (bytesOrStream) : bytesOrStream); try { if (Clazz.instanceOf (t, String) || Clazz.instanceOf (t, java.io.BufferedReader)) return t; var bis = t; if (JU.Rdr.isGzipS (bis)) bis = JU.Rdr.getUnzippedInputStream (this.vwr.getJzt (), bis); else if (JU.Rdr.isBZip2S (bis)) bis = JU.Rdr.getUnzippedInputStreamBZip2 (this.vwr.getJzt (), bis); if (forceInputStream && subFileList == null) return bis; if (JU.Rdr.isCompoundDocumentS (bis)) { var doc = J.api.Interface.getInterface ("JU.CompoundDocument", this.vwr, "file"); doc.setDocStream (this.vwr.getJzt (), bis); var s = doc.getAllDataFiles ("Molecule", "Input").toString (); return (forceInputStream ? JU.Rdr.getBIS (s.getBytes ()) : JU.Rdr.getBR (s)); }if (JU.Rdr.isMessagePackS (bis) || JU.Rdr.isPickleS (bis)) return bis; bis = JU.Rdr.getPngZipStream (bis, true); if (JU.Rdr.isZipS (bis)) { if (allowZipStream) return this.vwr.getJzt ().newZipInputStream (bis); var o = this.vwr.getJzt ().getZipFileDirectory (bis, subFileList, 1, forceInputStream); return (Clazz.instanceOf (o, String) ? JU.Rdr.getBR (o) : o); }return (forceInputStream ? bis : JU.Rdr.getBufferedReader (bis, null)); } catch (ioe) { if (Clazz.exceptionOf (ioe, Exception)) { return ioe.toString (); } else { throw ioe; } } }, "~S,~O,~B,~B,~B,~B,java.util.Map"); Clazz.defineMethod (c$, "getZipDirectory", function (fileName, addManifest, allowCached) { var t = this.getBufferedInputStreamOrErrorMessageFromName (fileName, fileName, false, false, null, false, allowCached); return this.vwr.getJzt ().getZipDirectoryAndClose (t, addManifest ? "JmolManifest" : null); }, "~S,~B,~B"); Clazz.defineMethod (c$, "getFileAsBytes", function (name, out) { if (name == null) return null; var fullName = name; var subFileList = null; if (name.indexOf ("|") >= 0) { subFileList = JU.PT.split (name, "|"); name = subFileList[0]; }var bytes = (subFileList == null ? null : this.getPngjOrDroppedBytes (fullName, name)); if (bytes == null) { var t = this.getBufferedInputStreamOrErrorMessageFromName (name, fullName, false, false, null, false, true); if (Clazz.instanceOf (t, String)) return "Error:" + t; try { var bis = t; bytes = (out != null || subFileList == null || subFileList.length <= 1 || !JU.Rdr.isZipS (bis) && !JU.Rdr.isPngZipStream (bis) ? JU.Rdr.getStreamAsBytes (bis, out) : this.vwr.getJzt ().getZipFileContentsAsBytes (bis, subFileList, 1)); bis.close (); } catch (ioe) { if (Clazz.exceptionOf (ioe, Exception)) { return ioe.toString (); } else { throw ioe; } } }if (out == null || !JU.AU.isAB (bytes)) return bytes; out.write (bytes, 0, -1); return (bytes).length + " bytes"; }, "~S,JU.OC"); Clazz.defineMethod (c$, "getFileAsMap", function (name, type) { var bdata = new java.util.Hashtable (); var t; if (name == null) { var errMsg = new Array (1); var bytes = this.vwr.getImageAsBytes (type, -1, -1, -1, errMsg); if (errMsg[0] != null) { bdata.put ("_ERROR_", errMsg[0]); return bdata; }t = JU.Rdr.getBIS (bytes); } else { var data = new Array (2); t = this.getFullPathNameOrError (name, true, data); if (Clazz.instanceOf (t, String)) { bdata.put ("_ERROR_", t); return bdata; }if (!this.checkSecurity (data[0])) { bdata.put ("_ERROR_", "java.io. Security exception: cannot read file " + data[0]); return bdata; }}try { this.vwr.getJzt ().readFileAsMap (t, bdata, name); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { bdata.clear (); bdata.put ("_ERROR_", "" + e); } else { throw e; } } return bdata; }, "~S,~S"); Clazz.defineMethod (c$, "getFileDataAsString", function (data, nBytesMax, doSpecialLoad, allowBinary, checkProtected) { data[1] = ""; var name = data[0]; if (name == null) return false; var t = this.getBufferedReaderOrErrorMessageFromName (name, data, false, doSpecialLoad); if (Clazz.instanceOf (t, String)) { data[1] = t; return false; }if (checkProtected && !this.checkSecurity (data[0])) { data[1] = "java.io. Security exception: cannot read file " + data[0]; return false; }try { return JU.Rdr.readAllAsString (t, nBytesMax, allowBinary, data, 1); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { return false; } else { throw e; } } }, "~A,~N,~B,~B,~B"); Clazz.defineMethod (c$, "checkSecurity", function (f) { if (!f.startsWith ("file:")) return true; var pt = f.lastIndexOf ('/'); if (f.lastIndexOf (":/") == pt - 1 || f.indexOf ("/.") >= 0 || f.lastIndexOf ('.') < f.lastIndexOf ('/')) return false; return true; }, "~S"); Clazz.defineMethod (c$, "loadImage", function (nameOrBytes, echoName, forceSync) { var image = null; var nameOrError = null; var bytes = null; var isPopupImage = (echoName != null && echoName.startsWith ("\1")); if (isPopupImage) { if (echoName.equals ("\1closeall\1null")) return this.vwr.loadImageData (Boolean.TRUE, "\1closeall", "\1closeall", null); if ("\1close".equals (nameOrBytes)) return this.vwr.loadImageData (Boolean.FALSE, "\1close", echoName, null); }if (Clazz.instanceOf (nameOrBytes, java.util.Map)) { nameOrBytes = ((nameOrBytes).containsKey ("_DATA_") ? (nameOrBytes).get ("_DATA_") : (nameOrBytes).get ("_IMAGE_")); }if (Clazz.instanceOf (nameOrBytes, JS.SV)) nameOrBytes = (nameOrBytes).value; var name = (Clazz.instanceOf (nameOrBytes, String) ? nameOrBytes : null); var isAsynchronous = false; if (name != null && name.startsWith (";base64,")) { bytes = JU.Base64.decodeBase64 (name); } else if (Clazz.instanceOf (nameOrBytes, JU.BArray)) { bytes = (nameOrBytes).data; } else if (echoName == null || Clazz.instanceOf (nameOrBytes, String)) { var names = this.getClassifiedName (nameOrBytes, true); nameOrError = (names == null ? "cannot read file name: " + nameOrBytes : JV.FileManager.fixDOSName (names[0])); if (names != null) image = this.getJzu ().getImage (this.vwr, nameOrError, echoName, forceSync); isAsynchronous = (image == null); } else { image = nameOrBytes; }if (bytes != null) { image = this.getJzu ().getImage (this.vwr, bytes, echoName, true); isAsynchronous = false; }if (Clazz.instanceOf (image, String)) { nameOrError = image; image = null; }if (!this.vwr.isJS && image != null && bytes != null) nameOrError = ";base64," + JU.Base64.getBase64 (bytes).toString (); if (!this.vwr.isJS || isPopupImage && nameOrError == null || !isPopupImage && image != null) return this.vwr.loadImageData (image, nameOrError, echoName, null); return isAsynchronous; }, "~O,~S,~B"); Clazz.defineMethod (c$, "getClassifiedName", function (name, isFullLoad) { if (name == null) return Clazz.newArray (-1, [null]); var doSetPathForAllFiles = (this.pathForAllFiles.length > 0); if (name.startsWith ("?") || name.startsWith ("http://?")) { if (!this.vwr.isJS && (name = this.vwr.dialogAsk ("Load", name, null)) == null) return Clazz.newArray (-1, [isFullLoad ? "#CANCELED#" : null]); doSetPathForAllFiles = false; }var file = null; var url = null; var names = null; if (name.startsWith ("cache://")) { names = new Array (3); names[0] = names[2] = name; names[1] = JV.FileManager.stripPath (names[0]); return names; }name = this.vwr.resolveDatabaseFormat (name); if (name.indexOf (":") < 0 && name.indexOf ("/") != 0) name = JV.FileManager.addDirectory (this.vwr.getDefaultDirectory (), name); if (this.appletDocumentBaseURL == null) { if (JU.OC.urlTypeIndex (name) >= 0 || this.vwr.haveAccess (JV.Viewer.ACCESS.NONE) || this.vwr.haveAccess (JV.Viewer.ACCESS.READSPT) && !name.endsWith (".spt") && !name.endsWith ("/")) { try { url = new java.net.URL (Clazz.castNullAs ("java.net.URL"), name, null); } catch (e) { if (Clazz.exceptionOf (e, java.net.MalformedURLException)) { return Clazz.newArray (-1, [isFullLoad ? e.toString () : null]); } else { throw e; } } } else { file = this.vwr.apiPlatform.newFile (name); var s = file.getFullPath (); var fname = file.getName (); names = Clazz.newArray (-1, [(s == null ? fname : s), fname, (s == null ? fname : "file:/" + s.$replace ('\\', '/'))]); }} else { try { if (name.indexOf (":\\") == 1 || name.indexOf (":/") == 1) name = "file:/" + name; url = new java.net.URL (this.appletDocumentBaseURL, name, null); } catch (e) { if (Clazz.exceptionOf (e, java.net.MalformedURLException)) { return Clazz.newArray (-1, [isFullLoad ? e.toString () : null]); } else { throw e; } } }if (url != null) { names = new Array (3); names[0] = names[2] = url.toString (); names[1] = JV.FileManager.stripPath (names[0]); }if (doSetPathForAllFiles) { var name0 = names[0]; names[0] = this.pathForAllFiles + names[1]; JU.Logger.info ("FileManager substituting " + name0 + " --> " + names[0]); }if (isFullLoad && (file != null || JU.OC.urlTypeIndex (names[0]) == 5)) { var path = (file == null ? JU.PT.trim (names[0].substring (5), "/") : names[0]); var pt = path.length - names[1].length - 1; if (pt > 0) { path = path.substring (0, pt); JV.FileManager.setLocalPath (this.vwr, path, true); }}return names; }, "~S,~B"); c$.addDirectory = Clazz.defineMethod (c$, "addDirectory", function (defaultDirectory, name) { if (defaultDirectory.length == 0) return name; var ch = (name.length > 0 ? name.charAt (0) : ' '); var s = defaultDirectory.toLowerCase (); if ((s.endsWith (".zip") || s.endsWith (".tar")) && ch != '|' && ch != '/') defaultDirectory += "|"; return defaultDirectory + (ch == '/' || ch == '/' || (ch = defaultDirectory.charAt (defaultDirectory.length - 1)) == '|' || ch == '/' ? "" : "/") + name; }, "~S,~S"); Clazz.defineMethod (c$, "getDefaultDirectory", function (name) { var names = this.getClassifiedName (name, true); if (names == null) return ""; name = JV.FileManager.fixPath (names[0]); return (name == null ? "" : name.substring (0, name.lastIndexOf ("/"))); }, "~S"); c$.fixPath = Clazz.defineMethod (c$, "fixPath", function (path) { path = JV.FileManager.fixDOSName (path); path = JU.PT.rep (path, "/./", "/"); var pt = path.lastIndexOf ("//") + 1; if (pt < 1) pt = path.indexOf (":/") + 1; if (pt < 1) pt = path.indexOf ("/"); if (pt < 0) return null; var protocol = path.substring (0, pt); path = path.substring (pt); while ((pt = path.lastIndexOf ("/../")) >= 0) { var pt0 = path.substring (0, pt).lastIndexOf ("/"); if (pt0 < 0) return JU.PT.rep (protocol + path, "/../", "/"); path = path.substring (0, pt0) + path.substring (pt + 3); } if (path.length == 0) path = "/"; return protocol + path; }, "~S"); Clazz.defineMethod (c$, "getFilePath", function (name, addUrlPrefix, asShortName) { var names = this.getClassifiedName (name, false); return (names == null || names.length == 1 ? "" : asShortName ? names[1] : addUrlPrefix ? names[2] : names[0] == null ? "" : JV.FileManager.fixDOSName (names[0])); }, "~S,~B,~B"); c$.getLocalDirectory = Clazz.defineMethod (c$, "getLocalDirectory", function (vwr, forDialog) { var localDir = vwr.getP (forDialog ? "currentLocalPath" : "defaultDirectoryLocal"); if (forDialog && localDir.length == 0) localDir = vwr.getP ("defaultDirectoryLocal"); if (localDir.length == 0) return (vwr.isApplet ? null : vwr.apiPlatform.newFile (System.getProperty ("user.dir", "."))); if (vwr.isApplet && localDir.indexOf ("file:/") == 0) localDir = localDir.substring (6); var f = vwr.apiPlatform.newFile (localDir); try { return f.isDirectory () ? f : f.getParentAsFile (); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { return null; } else { throw e; } } }, "JV.Viewer,~B"); c$.setLocalPath = Clazz.defineMethod (c$, "setLocalPath", function (vwr, path, forDialog) { while (path.endsWith ("/") || path.endsWith ("\\")) path = path.substring (0, path.length - 1); vwr.setStringProperty ("currentLocalPath", path); if (!forDialog) vwr.setStringProperty ("defaultDirectoryLocal", path); }, "JV.Viewer,~S,~B"); c$.getLocalPathForWritingFile = Clazz.defineMethod (c$, "getLocalPathForWritingFile", function (vwr, file) { if (file.startsWith ("http://")) return file; file = JU.PT.rep (file, "?", ""); if (file.indexOf ("file:/") == 0) return file.substring (6); if (file.indexOf ("/") == 0 || file.indexOf (":") >= 0) return file; var dir = null; try { dir = JV.FileManager.getLocalDirectory (vwr, false); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } return (dir == null ? file : JV.FileManager.fixPath (dir.toString () + "/" + file)); }, "JV.Viewer,~S"); c$.fixDOSName = Clazz.defineMethod (c$, "fixDOSName", function (fileName) { return (fileName.indexOf (":\\") >= 0 ? fileName.$replace ('\\', '/') : fileName); }, "~S"); c$.stripPath = Clazz.defineMethod (c$, "stripPath", function (name) { var pt = Math.max (name.lastIndexOf ("|"), name.lastIndexOf ("/")); return name.substring (pt + 1); }, "~S"); c$.determineSurfaceTypeIs = Clazz.defineMethod (c$, "determineSurfaceTypeIs", function (is) { var br; try { br = JU.Rdr.getBufferedReader ( new java.io.BufferedInputStream (is), "ISO-8859-1"); } catch (e) { if (Clazz.exceptionOf (e, java.io.IOException)) { return null; } else { throw e; } } return JV.FileManager.determineSurfaceFileType (br); }, "java.io.InputStream"); c$.isScriptType = Clazz.defineMethod (c$, "isScriptType", function (fname) { return JU.PT.isOneOf (fname.toLowerCase ().substring (fname.lastIndexOf (".") + 1), ";pse;spt;png;pngj;jmol;zip;"); }, "~S"); c$.isSurfaceType = Clazz.defineMethod (c$, "isSurfaceType", function (fname) { return JU.PT.isOneOf (fname.toLowerCase ().substring (fname.lastIndexOf (".") + 1), ";jvxl;kin;o;msms;map;pmesh;mrc;efvet;cube;obj;dssr;bcif;"); }, "~S"); c$.determineSurfaceFileType = Clazz.defineMethod (c$, "determineSurfaceFileType", function (bufferedReader) { var line = null; if (Clazz.instanceOf (bufferedReader, JU.Rdr.StreamReader)) { var is = (bufferedReader).getStream (); if (is.markSupported ()) { try { is.mark (300); var buf = Clazz.newByteArray (300, 0); is.read (buf, 0, 300); is.reset (); if ((buf[0] & 0xFF) == 0x83) return "BCifDensity"; if (buf[0] == 80 && buf[1] == 77 && buf[2] == 1 && buf[3] == 0) return "Pmesh"; if (buf[208] == 77 && buf[209] == 65 && buf[210] == 80) return "Mrc"; if (buf[0] == 20 && buf[1] == 0 && buf[2] == 0 && buf[3] == 0) return "DelPhi"; if (buf[36] == 0 && buf[37] == 100) return "Dsn6"; } catch (e) { if (Clazz.exceptionOf (e, java.io.IOException)) { } else { throw e; } } }}var br = null; try { br = new JU.LimitedLineReader (bufferedReader, 16000); line = br.getHeader (0); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } if (br == null || line == null || line.length == 0) return null; var pt0 = line.indexOf ('\0'); if (pt0 >= 0) { if (line.charCodeAt (0) == 0x83) return "BCifDensity"; if (line.indexOf ("PM\u0001\u0000") == 0) return "Pmesh"; if (line.indexOf ("MAP ") == 208) return "Mrc"; if (line.indexOf ("\u0014\u0000\u0000\u0000") == 0) return "DelPhi"; if (line.length > 37 && (line.charCodeAt (36) == 0 && line.charCodeAt (37) == 100 || line.charCodeAt (36) == 0 && line.charCodeAt (37) == 100)) { return "Dsn6"; }}switch (line.charAt (0)) { case '@': if (line.indexOf ("@text") == 0) return "Kinemage"; break; case '#': if (line.indexOf (".obj") >= 0) return "Obj"; if (line.indexOf ("MSMS") >= 0) return "Msms"; break; case '&': if (line.indexOf ("&plot") == 0) return "Jaguar"; break; case '\r': case '\n': if (line.indexOf ("ZYX") >= 0) return "Xplor"; break; } if (line.indexOf ("Here is your gzipped map") >= 0) return "UPPSALA" + line; if (line.startsWith ("data_SERVER")) return "CifDensity"; if (line.startsWith ("4MESHC")) return "Pmesh4"; if (line.indexOf ("! nspins") >= 0) return "CastepDensity"; if (line.indexOf ("<jvxl") >= 0 && line.indexOf ("<?xml") >= 0) return "JvxlXml"; if (line.indexOf ("#JVXL+") >= 0) return "Jvxl+"; if (line.indexOf ("#JVXL") >= 0) return "Jvxl"; if (line.indexOf ("#JmolPmesh") >= 0) return "Pmesh"; if (line.indexOf ("#obj") >= 0) return "Obj"; if (line.indexOf ("#pmesh") >= 0) return "Obj"; if (line.indexOf ("<efvet ") >= 0) return "Efvet"; if (line.indexOf ("usemtl") >= 0) return "Obj"; if (line.indexOf ("# object with") == 0) return "Nff"; if (line.indexOf ("BEGIN_DATAGRID_3D") >= 0 || line.indexOf ("BEGIN_BANDGRID_3D") >= 0) return "Xsf"; if (line.indexOf ("tiles in x, y") >= 0) return "Ras3D"; if (line.indexOf (" 0.00000e+00 0.00000e+00 0 0\n") >= 0) return "Uhbd"; line = br.readLineWithNewline (); if (line.indexOf ("object 1 class gridpositions counts") == 0) return "Apbs"; var tokens = JU.PT.getTokens (line); var line2 = br.readLineWithNewline (); if (tokens.length == 2 && JU.PT.parseInt (tokens[0]) == 3 && JU.PT.parseInt (tokens[1]) != -2147483648) { tokens = JU.PT.getTokens (line2); if (tokens.length == 3 && JU.PT.parseInt (tokens[0]) != -2147483648 && JU.PT.parseInt (tokens[1]) != -2147483648 && JU.PT.parseInt (tokens[2]) != -2147483648) return "PltFormatted"; }var line3 = br.readLineWithNewline (); if (line.startsWith ("v ") && line2.startsWith ("v ") && line3.startsWith ("v ")) return "Obj"; var nAtoms = JU.PT.parseInt (line3); if (nAtoms == -2147483648) return (line3.indexOf ("+") == 0 ? "Jvxl+" : null); tokens = JU.PT.getTokens (line3); if (tokens[0].indexOf (".") > 0) return (line3.length >= 60 || tokens.length != 3 ? null : "VaspChgcar"); if (nAtoms >= 0) return (tokens.length == 4 || tokens.length == 5 && tokens[4].equals ("1") ? "Cube" : null); nAtoms = -nAtoms; for (var i = 4 + nAtoms; --i >= 0; ) if ((line = br.readLineWithNewline ()) == null) return null; var nSurfaces = JU.PT.parseInt (line); if (nSurfaces == -2147483648) return null; return (nSurfaces < 0 ? "Jvxl" : "Cube"); }, "java.io.BufferedReader"); c$.getManifestScriptPath = Clazz.defineMethod (c$, "getManifestScriptPath", function (manifest) { if (manifest.indexOf ("$SCRIPT_PATH$") >= 0) return ""; var ch = (manifest.indexOf ('\n') >= 0 ? "\n" : "\r"); if (manifest.indexOf (".spt") >= 0) { var s = JU.PT.split (manifest, ch); for (var i = s.length; --i >= 0; ) if (s[i].indexOf (".spt") >= 0) return "|" + JU.PT.trim (s[i], "\r\n \t"); }return null; }, "~S"); c$.getEmbeddedScript = Clazz.defineMethod (c$, "getEmbeddedScript", function (script) { if (script == null) return script; var pt = script.indexOf ("**** Jmol Embedded Script ****"); if (pt < 0) return script; var pt1 = script.lastIndexOf ("/*", pt); var pt2 = script.indexOf ((script.charAt (pt1 + 2) == '*' ? "*" : "") + "*/", pt); if (pt1 >= 0 && pt2 >= pt) script = script.substring (pt + "**** Jmol Embedded Script ****".length, pt2) + "\n"; while ((pt1 = script.indexOf (" #Jmol...\u0000")) >= 0) script = script.substring (0, pt1) + script.substring (pt1 + " #Jmol...\u0000".length + 4); if (JU.Logger.debugging) JU.Logger.debug (script); return script; }, "~S"); c$.getFileReferences = Clazz.defineMethod (c$, "getFileReferences", function (script, fileList) { for (var ipt = 0; ipt < JV.FileManager.scriptFilePrefixes.length; ipt++) { var tag = JV.FileManager.scriptFilePrefixes[ipt]; var i = -1; while ((i = script.indexOf (tag, i + 1)) >= 0) { var s = JU.PT.getQuotedStringAt (script, i); if (s.indexOf ("::") >= 0) s = JU.PT.split (s, "::")[1]; fileList.addLast (s); } } }, "~S,JU.Lst"); c$.setScriptFileReferences = Clazz.defineMethod (c$, "setScriptFileReferences", function (script, localPath, remotePath, scriptPath) { if (localPath != null) script = JV.FileManager.setScriptFileRefs (script, localPath, true); if (remotePath != null) script = JV.FileManager.setScriptFileRefs (script, remotePath, false); script = JU.PT.rep (script, "\1\"", "\""); if (scriptPath != null) { while (scriptPath.endsWith ("/")) scriptPath = scriptPath.substring (0, scriptPath.length - 1); for (var ipt = 0; ipt < JV.FileManager.scriptFilePrefixes.length; ipt++) { var tag = JV.FileManager.scriptFilePrefixes[ipt]; script = JU.PT.rep (script, tag + ".", tag + scriptPath); } }return script; }, "~S,~S,~S,~S"); c$.setScriptFileRefs = Clazz.defineMethod (c$, "setScriptFileRefs", function (script, dataPath, isLocal) { if (dataPath == null) return script; var noPath = (dataPath.length == 0); var fileNames = new JU.Lst (); JV.FileManager.getFileReferences (script, fileNames); var oldFileNames = new JU.Lst (); var newFileNames = new JU.Lst (); var nFiles = fileNames.size (); for (var iFile = 0; iFile < nFiles; iFile++) { var name0 = fileNames.get (iFile); var name = name0; if (isLocal == JU.OC.isLocal (name)) { var pt = (noPath ? -1 : name.indexOf ("/" + dataPath + "/")); if (pt >= 0) { name = name.substring (pt + 1); } else { pt = name.lastIndexOf ("/"); if (pt < 0 && !noPath) name = "/" + name; if (pt < 0 || noPath) pt++; name = dataPath + name.substring (pt); }}JU.Logger.info ("FileManager substituting " + name0 + " --> " + name); oldFileNames.addLast ("\"" + name0 + "\""); newFileNames.addLast ("\1\"" + name + "\""); } return JU.PT.replaceStrings (script, oldFileNames, newFileNames); }, "~S,~S,~B"); Clazz.defineMethod (c$, "cachePut", function (key, data) { key = JV.FileManager.fixDOSName (key); if (JU.Logger.debugging) JU.Logger.debug ("cachePut " + key); if (data == null || "".equals (data)) { this.cache.remove (key); return; }this.cache.put (key, data); this.getCachedPngjBytes (key); }, "~S,~O"); Clazz.defineMethod (c$, "cacheGet", function (key, bytesOnly) { key = JV.FileManager.fixDOSName (key); var pt = key.indexOf ("|"); if (pt >= 0 && !key.endsWith ("##JmolSurfaceInfo##")) key = key.substring (0, pt); key = this.getFilePath (key, true, false); var data = null; { (data = Jmol.Cache.get(key)) || (data = this.cache.get(key)); }return (bytesOnly && (Clazz.instanceOf (data, String)) ? null : data); }, "~S,~B"); Clazz.defineMethod (c$, "cacheClear", function () { JU.Logger.info ("cache cleared"); this.cache.clear (); if (this.pngjCache == null) return; this.pngjCache = null; JU.Logger.info ("PNGJ cache cleared"); }); Clazz.defineMethod (c$, "cacheFileByNameAdd", function (fileName, isAdd) { if (fileName == null || !isAdd && fileName.equalsIgnoreCase ("")) { this.cacheClear (); return -1; }var data; if (isAdd) { fileName = JV.JC.fixProtocol (this.vwr.resolveDatabaseFormat (fileName)); data = this.getFileAsBytes (fileName, null); if (Clazz.instanceOf (data, String)) return 0; this.cachePut (fileName, data); } else { if (fileName.endsWith ("*")) return JU.AU.removeMapKeys (this.cache, fileName.substring (0, fileName.length - 1)); data = this.cache.remove (JV.FileManager.fixDOSName (fileName)); }return (data == null ? 0 : Clazz.instanceOf (data, String) ? (data).length : (data).length); }, "~S,~B"); Clazz.defineMethod (c$, "cacheList", function () { var map = new java.util.Hashtable (); for (var entry, $entry = this.cache.entrySet ().iterator (); $entry.hasNext () && ((entry = $entry.next ()) || true);) map.put (entry.getKey (), Integer.$valueOf (JU.AU.isAB (entry.getValue ()) ? (entry.getValue ()).length : entry.getValue ().toString ().length)); return map; }); Clazz.defineMethod (c$, "getCanonicalName", function (pathName) { var names = this.getClassifiedName (pathName, true); return (names == null ? pathName : names[2]); }, "~S"); Clazz.defineMethod (c$, "recachePngjBytes", function (fileName, bytes) { if (this.pngjCache == null || !this.pngjCache.containsKey (fileName)) return; this.pngjCache.put (fileName, bytes); JU.Logger.info ("PNGJ recaching " + fileName + " (" + bytes.length + ")"); }, "~S,~A"); Clazz.defineMethod (c$, "getPngjOrDroppedBytes", function (fullName, name) { var bytes = this.getCachedPngjBytes (fullName); return (bytes == null ? this.cacheGet (name, true) : bytes); }, "~S,~S"); Clazz.defineMethod (c$, "getCachedPngjBytes", function (pathName) { return (pathName == null || this.pngjCache == null || pathName.indexOf (".png") < 0 ? null : this.getJzu ().getCachedPngjBytes (this, pathName)); }, "~S"); Clazz.overrideMethod (c$, "postByteArray", function (fileName, bytes) { if (fileName.startsWith ("cache://")) { this.cachePut (fileName, bytes); return "OK " + bytes.length + "cached"; }var ret = this.getBufferedInputStreamOrErrorMessageFromName (fileName, null, false, false, bytes, false, true); if (Clazz.instanceOf (ret, String)) return ret; try { ret = JU.Rdr.getStreamAsBytes (ret, null); } catch (e) { if (Clazz.exceptionOf (e, java.io.IOException)) { try { (ret).close (); } catch (e1) { if (Clazz.exceptionOf (e1, java.io.IOException)) { } else { throw e1; } } } else { throw e; } } return (ret == null ? "" : JU.Rdr.fixUTF (ret)); }, "~S,~A"); Clazz.defineStatics (c$, "SIMULATION_PROTOCOL", "http://SIMULATION/", "DELPHI_BINARY_MAGIC_NUMBER", "\24\0\0\0", "PMESH_BINARY_MAGIC_NUMBER", "PM\1\0", "JPEG_CONTINUE_STRING", " #Jmol...\0"); c$.scriptFilePrefixes = c$.prototype.scriptFilePrefixes = Clazz.newArray (-1, ["/*file*/\"", "FILE0=\"", "FILE1=\""]); });
import { FETCH_REPORT_LINKAGE } from '../actions/BusinessRulesAction'; // TODO: export default function(state=[], action) { console.log("Action received in report linkage: ", action); switch(action.type) { case FETCH_REPORT_LINKAGE: state = []; return state.concat(action.payload.data); default: return state; } }
(function(){/* MIT License (c) copyright 2010-2013 B Cavalier & J Hann */ (function(m){function T(){}function t(a,b){return 0==Z.call(a).indexOf("[object "+b)}function H(a){return a&&"/"==a.charAt(a.length-1)?a.substr(0,a.length-1):a}function U(a,b){var d,c,e,f;d=1;c=a;"."==c.charAt(0)&&(e=!0,c=c.replace($,function(a,b,c,e){c&&d++;return e||""}));if(e){e=b.split("/");f=e.length-d;if(0>f)return a;e.splice(f,d);return e.concat(c||[]).join("/")}return c}function I(a){var b=a.indexOf("!");return{f:a.substr(b+1),d:0<=b&&a.substr(0,b)}}function O(){}function u(a,b){O.prototype= a||P;var d=new O;O.prototype=P;for(var c in b)d[c]=b[c];return d}function J(){function a(a,b,d){c.push([a,b,d])}function b(a,b){for(var d,e=0;d=c[e++];)(d=d[a])&&d(b)}var d,c,e;d=this;c=[];e=function(d,g){a=d?function(a){a&&a(g)}:function(a,b){b&&b(g)};e=T;b(d?0:1,g);b=T;c=k};this.then=function(b,c,e){a(b,c,e);return d};this.h=function(a){d.oa=a;e(!0,a)};this.g=function(a){d.na=a;e(!1,a)};this.u=function(a){b(2,a)}}function K(a){return a instanceof J||a instanceof A}function v(a,b,d,c){K(a)?a.then(b, d,c):b(a)}function B(a,b,d){var c;return function(){0<=--a&&b&&(c=b.apply(k,arguments));0==a&&d&&d(c);return c}}function z(){var a,b;C="";a=[].slice.call(arguments);t(a[0],"Object")&&(b=a.shift(),b=L(b));return new A(a[0],a[1],a[2],b)}function L(a,b,d){var c;C="";if(a&&(h.O(a),w=h.a(a),"preloads"in a&&(c=new A(a.preloads,k,d,D,!0),h.l(function(){D=c})),a=a.main))return new A(a,b,d)}function A(a,b,d,c,e){var f;f=h.j(w,k,[].concat(a),e);this.then=this.then=a=function(a,b){v(f,function(b){a&&a.apply(k, b)},function(a){if(b)b(a);else throw a;});return this};this.next=function(a,b,c){return new A(a,b,c,f)};this.config=L;(b||d)&&a(b,d);h.l(function(){v(e||D,function(){v(c,function(){h.q(f)},d)})})}function V(a){var b,d;b=a.id;b==k&&(E!==k?E={F:"Multiple anonymous defines encountered"}:(b=h.aa())||(E=a));if(b!=k){d=l[b];b in l||(d=h.i(b,w),d=h.B(d.a,b),l[b]=d);if(!K(d))throw Error("duplicate define: "+b);d.ca=!1;h.C(d,a)}}function Q(){var a=h.Y(arguments);V(a)}var C,w,x,F,y=m.document,R=y&&(y.head|| y.getElementsByTagName("head")[0]),aa=R&&R.getElementsByTagName("base")[0]||null,W={},X={},M={},ba="addEventListener"in m?{}:{loaded:1,complete:1},P={},Z=P.toString,k,l={},N={},D=!1,E,Y=/^\/|^[^:]+:\/\//,$=/(\.)(\.?)(?:$|\/([^\.\/]+.*)?)/g,ca=/\/\*[\s\S]*?\*\/|\/\/.*?[\n\r]/g,da=/require\s*\(\s*(["'])(.*?[^\\])\1\s*\)|[^\\]?(["'])/g,ea=/\s*,\s*/,S,h;h={m:function(a,b,d){var c;a=U(a,b);if("."==a.charAt(0))return a;c=I(a);a=(b=c.d)||c.f;a in d.c&&(a=d.c[a].K||a);b&&(0>b.indexOf("/")&&!(b in d.c)&&(a= H(d.M)+"/"+b),a=a+"!"+c.f);return a},j:function(a,b,d,c){function e(b,c){var d,f;d=h.m(b,g.id,a);if(!c)return d;f=I(d);if(!f.d)return d;d=l[f.d];f.f="normalize"in d?d.normalize(f.f,e,g.a)||"":e(f.f);return f.d+"!"+f.f}function f(b,d,f){var p;p=d&&function(a){d.apply(k,a)};if(t(b,"String")){if(p)throw Error("require(id, callback) not allowed");f=e(b,!0);b=l[f];if(!(f in l))throw Error("Module not resolved: "+f);return(f=K(b)&&b.b)||b}v(h.q(h.j(a,g.id,b,c)),p,f)}var g;g=new J;g.id=b||"";g.ba=c;g.D= d;g.a=a;g.v=f;f.toUrl=function(b){return h.i(e(b,!0),a).url};g.m=e;return g},B:function(a,b,d){var c,e,f;c=h.j(a,b,k,d);e=c.h;f=B(1,function(a){c.p=a;try{return h.S(c)}catch(b){c.g(b)}});c.h=function(a){v(d||D,function(){e(l[c.id]=N[c.url]=f(a))})};c.G=function(a){v(d||D,function(){c.b&&(f(a),c.u(X))})};return c},R:function(a,b,d,c){return h.j(a,d,k,c)},$:function(a){return a.v},H:function(a){return a.b||(a.b={})},Z:function(a){var b=a.r;b||(b=a.r={id:a.id,uri:h.I(a),exports:h.H(a),config:function(){return a.a}}, b.b=b.exports);return b},I:function(a){return a.url||(a.url=h.A(a.v.toUrl(a.id),a.a))},O:function(a){var b,d,c,e,f;b="curl";d="define";c=e=m;if(a&&(f=a.overwriteApi||a.la,b=a.apiName||a.ea||b,c=a.apiContext||a.da||c,d=a.defineName||a.ga||d,e=a.defineContext||a.fa||e,x&&t(x,"Function")&&(m.curl=x),x=null,F&&t(F,"Function")&&(m.define=F),F=null,!f)){if(c[b]&&c[b]!=z)throw Error(b+" already exists");if(e[d]&&e[d]!=Q)throw Error(d+" already exists");}c[b]=z;e[d]=Q},a:function(a){function b(a,b){var d, c,g,n,q;for(q in a){g=a[q];t(g,"String")&&(g={path:a[q]});g.name=g.name||q;n=e;c=I(H(g.name));d=c.f;if(c=c.d)n=f[c],n||(n=f[c]=u(e),n.c=u(e.c),n.e=[]),delete a[q];c=g;var l=b,G=void 0;c.path=H(c.path||c.location||"");l&&(G=c.main||"./main","."==G.charAt(0)||(G="./"+G),c.K=U(G,c.name+"/"));c.a=c.config;c.a&&(c.a=u(e,c.a));c.P=d.split("/").length;d?(n.c[d]=c,n.e.push(d)):n.n=h.N(g.path,e)}}function d(a){var b=a.c;a.L=RegExp("^("+a.e.sort(function(a,c){return b[c].P-b[a].P}).join("|").replace(/\/|\./g, "\\$&")+")(?=\\/|$)");delete a.e}var c,e,f,g;"baseUrl"in a&&(a.n=a.baseUrl);"main"in a&&(a.K=a.main);"preloads"in a&&(a.ma=a.preloads);"pluginPath"in a&&(a.M=a.pluginPath);if("dontAddFileExt"in a||a.k)a.k=RegExp(a.dontAddFileExt||a.k);c=w;e=u(c,a);e.c=u(c.c);f=a.plugins||{};e.plugins=u(c.plugins);e.t=u(c.t,a.t);e.s=u(c.s,a.s);e.e=[];b(a.packages,!0);b(a.paths,!1);for(g in f)a=h.m(g+"!","",e),e.plugins[a.substr(0,a.length-1)]=f[g];f=e.plugins;for(g in f)if(f[g]=u(e,f[g]),a=f[g].e)f[g].e=a.concat(e.e), d(f[g]);for(g in c.c)e.c.hasOwnProperty(g)||e.e.push(g);d(e);return e},i:function(a,b){var d,c,e,f;d=b.c;e=Y.test(a)?a:a.replace(b.L,function(a){c=d[a]||{};f=c.a;return c.path||""});return{a:f||w,url:h.N(e,b)}},N:function(a,b){var d=b.n;return d&&!Y.test(a)?H(d)+"/"+a:a},A:function(a,b){return a+((b||w).k.test(a)?"":".js")},J:function(a,b,d){var c=y.createElement("script");c.onload=c.onreadystatechange=function(d){d=d||m.event;if("load"==d.type||ba[c.readyState])delete M[a.id],c.onload=c.onreadystatechange= c.onerror="",b()};c.onerror=function(){d(Error("Syntax or http error: "+a.url))};c.type=a.ia||"text/javascript";c.charset="utf-8";c.async=!a.ka;c.src=a.url;M[a.id]=c;R.insertBefore(c,aa);return c},T:function(a){var b=[],d;("string"==typeof a?a:a.toSource?a.toSource():a.toString()).replace(ca,"").replace(da,function(a,e,f,g){g?d=d==g?k:d:d||b.push(f);return""});return b},Y:function(a){var b,d,c,e,f,g;f=a.length;c=a[f-1];e=t(c,"Function")?c.length:-1;2==f?t(a[0],"Array")?d=a[0]:b=a[0]:3==f&&(b=a[0], d=a[1]);!d&&0<e&&(g=!0,d=["require","exports","module"].slice(0,e).concat(h.T(c)));return{id:b,p:d||[],w:0<=e?c:function(){return c},o:g}},S:function(a){var b;b=a.w.apply(a.o?a.b:k,a.p);b===k&&a.b&&(b=a.r?a.b=a.r.exports:a.b);return b},C:function(a,b){a.w=b.w;a.o=b.o;a.D=b.p;h.q(a)},q:function(a){function b(a,b,c){g[b]=a;c&&r(a,b)}function d(b,c){var d,e,f,g;d=B(1,function(a){e(a);p(a,c)});e=B(1,function(a){r(a,c)});f=h.V(b,a);(g=K(f)&&f.b)&&e(g);v(f,d,a.g,a.b&&function(a){f.b&&(a==W?e(f.b):a==X&& d(f.b))})}function c(){a.h(g)}var e,f,g,l,s,r,p;g=[];f=a.D;l=f.length;0==f.length&&c();r=B(l,b,function(){a.G&&a.G(g)});p=B(l,b,c);for(e=0;e<l;e++)s=f[e],s in S?(p(S[s](a),e,!0),a.b&&a.u(W)):s?d(s,e):p(k,e,!0);return a},W:function(a){h.I(a);h.J(a,function(){var b=E;E=k;!1!==a.ca&&(!b||b.F?a.g(Error(b&&b.F||"define() missing or duplicated: "+a.url)):h.C(a,b))},a.g);return a},V:function(a,b){var d,c,e,f,g,k,s,r,p,m,n,q;d=b.m;c=b.ba;e=b.a||w;g=d(a);g in l?k=g:(f=I(g),r=f.f,k=f.d||r,p=h.i(k,e));if(!(g in l))if(q=h.i(r,e).a,f.d)s=k;else if(s=q.moduleLoader||q.ja||q.loader||q.ha)r=k,k=s,p=h.i(s,e);k in l?m=l[k]:p.url in N?m=l[k]=N[p.url]:(m=h.B(q,k,c),m.url=h.A(p.url,p.a),l[k]=N[p.url]=m,h.W(m));k==s&&(f.d&&e.plugins[f.d]&&(q=e.plugins[f.d]),n=new J,v(m,function(a){var b,e,f;f=a.dynamic;r="normalize"in a?a.normalize(r,d,m.a)||"":d(r);e=s+"!"+r;b=l[e];if(!(e in l)){b=h.R(q,e,r,c);f||(l[e]=b);var g=function(a){f||(l[e]=a);b.h(a)};g.resolve=g;g.reject=g.error=b.g;a.load(r,b.v,g,q)}n!=b&&v(b,n.h,n.g,n.u)}, n.g));return n||m},aa:function(){var a;if(!t(m.opera,"Opera"))for(var b in M)if("interactive"==M[b].readyState){a=b;break}return a},X:function(a){var b=0,d,c;for(d=y&&(y.scripts||y.getElementsByTagName("script"));d&&(c=d[b++]);)if(a(c))return c},U:function(){var a,b="";(a=h.X(function(a){(a=a.getAttribute("data-curl-run"))&&(b=a);return a}))&&a.setAttribute("data-curl-run","");return b},Q:function(){function a(){h.J({url:c.shift()},b,b)}function b(){C&&(c.length?(h.l(d),a()):d("run.js script did not run."))} function d(a){throw Error(a||"Primary run.js failed. Trying fallback.");}var c=C.split(ea);c.length&&a()},l:function(a){setTimeout(a,0)}};S={require:h.$,exports:h.H,module:h.Z};z.version="0.8.10";z.config=L;Q.amd={plugins:!0,jQuery:!0,curl:"0.8.10"};w={n:"",M:"curl/plugin",k:/\?|\.js\b/,t:{},s:{},plugins:{},c:{},L:/$^/};x=m.curl;F=m.define;x&&t(x,"Object")?(m.curl=k,L(x)):h.O();(C=h.U())&&h.l(h.Q);l.curl=z;l["curl/_privileged"]={core:h,cache:l,config:function(){return w},_define:V,_curl:z,Promise:J}})(this.window|| "undefined"!=typeof global&&global||this); }).call(this);
/*********FILE********** /features/engine/gears.js ********************/ // The initGears method is Copyright 2007, Google Inc. var storage = { engine: "gears", dbName: 'SJSDatabase', tableName: 'SJSStorageTable', db: null, init: function(){ this.initGears(); this.db = google.gears.factory.create('beta.database'); this.db.open(this.dbName); this.db.execute('CREATE TABLE IF NOT EXISTS ' + this.tableName + ' ( key TEXT PRIMARY KEY, value TEXT )'); }, get: function(key){ var rs = this.db.execute('SELECT value FROM ' + this.tableName + ' WHERE key = ?', [key]); var value = null; if(rs.isValidRow() && rs.fieldCount() > 0) { value = rs.field(0); } rs.close(); return value; }, set: function(key, value){ if(this.get(key) === null){ // no such key present, insert this.db.execute('INSERT INTO ' + this.tableName + ' values (?, ?)', [key, value]); }else{ // update this.db.execute('UPDATE ' + this.tableName + ' SET value = ? WHERE key = ?', [value, key]); } }, remove: function(key){ this.db.execute('DELETE FROM ' + this.tableName + ' WHERE key = ?', [key]); }, initGears: function(){ if (window.google && google.gears) { return; } var factory = null; // Firefox if (typeof GearsFactory != 'undefined') { factory = new GearsFactory(); } else { // IE try { factory = new ActiveXObject('Gears.Factory'); // privateSetGlobalObject is only required and supported on IE Mobile on // WinCE. if (factory.getBuildInfo().indexOf('ie_mobile') != -1) { factory.privateSetGlobalObject(this); } } catch (e) { // Safari if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) { factory = document.createElement("object"); factory.style.display = "none"; factory.width = 0; factory.height = 0; factory.type = "application/x-googlegears"; document.documentElement.appendChild(factory); if(factory && (typeof factory.create == 'undefined')) { // If NP_Initialize() returns an error, factory will still be created. // We need to make sure this case doesn't cause Gears to appear to // have been initialized. factory = null; } } } } // *Do not* define any objects if Gears is not installed. This mimics the // behavior of Gears defining the objects in the future. if (!factory) { return; } // Now set up the objects, being careful not to overwrite anything. // // Note: In Internet Explorer for Windows Mobile, you can't add properties to // the window object. However, global objects are automatically added as // properties of the window object in all browsers. if (!window.google) { google = {}; } if (!google.gears) { google.gears = {factory: factory}; } } }; storage.init(); /*********FILE********** /features/clear/gears.js ********************/ storage.clear = function(){ this.db.execute('DELETE FROM ' + this.tableName); }; /*********FILE********** /features/getAll/gears.js ********************/ storage.getAll = function(){ var all = []; var rs = this.db.execute('SELECT * FROM ' + this.tableName); var index = 0; while (rs.isValidRow() && rs.fieldCount() > 1) { all.push({key: rs.fieldByName('key'), value: rs.fieldByName('value')}); rs.next(); } rs.close(); return all; }; /*********FILE********** /features/getAllKeys/gears.js ********************/ storage.getAllKeys = function(){ var keys = []; var rs = this.db.execute('SELECT key FROM ' + this.tableName); var index = 0; while (rs.isValidRow() && rs.fieldCount() > 0) { keys.push(rs.field(0)); rs.next(); } rs.close(); return keys; };
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; define(["require", "exports", '../../../auth-service', '../services/user-service', '../models/user-models', 'aurelia-framework', 'aurelia-router'], function (require, exports, auth, userServices, models, aurelia_framework_1, aurelia_router_1) { "use strict"; var LoginViewModel = (function () { function LoginViewModel(userService, authService, router) { this.router = router; this.userService = userService; this.authService = authService; this.userLoginDto = new models.UserLoginModel(); } LoginViewModel.prototype.login = function () { var _this = this; this.userService.login(this.userLoginDto).then(function (result) { _this.authService.setAccessToken(result, _this.userLoginDto.rememberMe); _this.getUserSelfInfo().then(function () { Materialize.toast("welcome " + _this.authService.user.userName, 4000, 'btn'); _this.router.navigate('#/project/dashboard'); }); }); }; LoginViewModel.prototype.getUserSelfInfo = function () { var _this = this; return this.userService.getUserSelfInfo().then(function (result) { var user = { userName: result.userName, roles: result.roles, projects: result.projects }; _this.authService.setUser(user); }); }; LoginViewModel = __decorate([ aurelia_framework_1.inject(userServices.UserService, auth.AuthService, aurelia_router_1.Router), __metadata('design:paramtypes', [userServices.UserService, auth.AuthService, aurelia_router_1.Router]) ], LoginViewModel); return LoginViewModel; }()); exports.LoginViewModel = LoginViewModel; }); //# sourceMappingURL=login.js.map
import _ from 'lodash'; export default class DecSection { constructor(name) { this.name = name; this.nodes = []; } get html() { const htmls = _.map(this.nodes, node => node.html); return htmls.join('\n'); } append(node) { this.nodes.push(node); } }
export const ic_center_focus_weak_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm7 3c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm7-11h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4z"},"children":[]}]};
/*global require, define */ if ( typeof require === 'function' && require.config ) { require.config( { baseUrl: '../src', paths: { 'jquery': '../libs/jquery/jquery.min', 'visualcaptcha.jquery': './visualcaptcha.jquery' } } ); if ( location.href.indexOf( '-dist' ) !== -1 ) { require.config( { paths: { 'jquery': '../libs/jquery/jquery.min', 'visualcaptcha.jquery': '../dist/visualcaptcha.jquery' } } ); } } (function( root, factory ) { 'use strict'; if ( typeof define === 'function' && define.amd ) { define([ 'jquery', 'visualcaptcha.jquery' ], factory ); } else { factory( root.$ ); } }( this, function( $ ) { 'use strict'; /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ test( 'validate functions', function() { expect( 2 ); equal( typeof $.fn === 'object', true ); equal( typeof $.fn.visualCaptcha === 'function', true ); } ); } ));
a(1, function() {}, 2);
module.exports = { scripts: { "transition": true, "alert": true, "button": true, "carousel": true, "collapse": true, "dropdown": true, "modal": true, "tooltip": true, "popover": true, "scrollspy": true, "tab": true, "affix": true }, styles: { "mixins": true, "normalize": true, "print": true, "scaffolding": true, "type": true, "code": true, "grid": true, "tables": true, "forms": true, "buttons": true, "component-animations": true, "glyphicons": true, "dropdowns": true, "button-groups": true, "input-groups": true, "navs": true, "navbar": true, "breadcrumbs": true, "pagination": true, "pager": true, "labels": true, "badges": true, "jumbotron": true, "thumbnails": true, "alerts": true, "progress-bars": true, "media": true, "list-group": true, "panels": true, "wells": true, "close": true, "modals": true, "tooltip": true, "popovers": true, "carousel": true, "utilities": true, "responsive-utilities": true } };
"use strict" const dom = require('../dom.js') const utils = require('../utils.js') function createUploadModal(addFilesCb) { var uploadWindow = dom.modal("Upload Attachments", true) var fileArray = [] var fileList = dom.table(["", "File", "Size"]) fileList.classList.add("invisible") function addFiles(files) { for(var file of files) { fileArray.push(file) var tr = dom.tr([ "", file.name, utils.bytesText(file.size) ]) if(file.size > 1000000) { // tr.firstChild.innerHTML = icons.warning + " Too big" } fileList.appendChild(tr) } if(fileArray.length) { uploadAction.classList.remove("button-disabled") } input.value = null fileList.classList.remove("invisible") dropzone.classList.add("dropzone-short") } var dropzone = dom.div("", "dropzone") var dropzoneInside = dom.div() var input = dom.element("input", "", "no-margin-right") input.type = "file" input.multiple = true input.accept = "image/*" input.onchange = () => { addFiles(input.files) } dropzoneInside.appendChild(dom.div("Drag & Drop Files")) dropzoneInside.appendChild(dom.div("-- or --")) dropzoneInside.appendChild(input) dropzone.appendChild(dropzoneInside) dropzone.addEventListener("drop", event => { event.preventDefault() if(event.dataTransfer.files) { addFiles(event.dataTransfer.files) } dropzone.classList.remove("dropzone-active") }) dropzone.addEventListener("dragover", event => { event.preventDefault() }) dropzone.addEventListener("dragenter", event => { dropzone.classList.add("dropzone-active") }) dropzone.addEventListener("dragleave", event => { dropzone.classList.remove("dropzone-active") }) var actions = dom.div("", "modal-actions") var cancelAction = dom.span("Cancel", "button") cancelAction.addEventListener("click", () => { uploadWindow.hide() }) var uploadAction = dom.span("Upload", ["button", "button-disabled"]) uploadAction.addEventListener("click", () => { addFilesCb(fileArray) uploadWindow.hide() }) actions.appendChild(cancelAction) actions.appendChild(uploadAction) uploadWindow.appendChild(dropzone) uploadWindow.appendChild(fileList) uploadWindow.appendChild(actions) return uploadWindow } module.exports = createUploadModal
version https://git-lfs.github.com/spec/v1 oid sha256:0a291d50373a71839f28e085f89ececd0681ee6c88ab3272c92edbdc59d09a84 size 9756
import mongoose from 'mongoose'; export default conf => { mongoose.Promise = global.Promise; mongoose.connect(conf); mongoose.connection .once('open', () => console.log(`Connected to MongoDB: ${conf}`)) // eslint-disable-line .on('error', err => console.warn('Warning', err)); // eslint-disable-line };
import React from 'react'; import HeaderNav from './components/header'; const Template = ( props ) => { return ( <div> <HeaderNav/> <div className="container" > { props.children } </div> </div> ) } export default Template;
/** * This bootstraps the init framework * * @name bootstrap */ 'use strict'; module.exports = function(mmm) { // Add services modules to mmm mmm.events.on('post-bootstrap', 1, function(mmm) { // Load our tasks mmm.tasks.add('config', require('./tasks/config')(mmm)); mmm.tasks.add('version', require('./tasks/version')(mmm)); }); };
import fetch from 'isomorphic-fetch'; export function fetchExchangeRates(base, target) { if (!target.includes(base)) target.push(base); const exchangeServiceUrl = process.env.REACT_APP_XCHANGE_URL; const pairs = target.map(code => `${base}${code}`); return fetch(`${exchangeServiceUrl}?pairs=${pairs.join(',')}`) .then(body => body.json()) .then(response => response.rates.reduce((result, row) => { result[row.id.substring(3)] = parseFloat(row['rate']); return result; }, {}) ); }
var model = require("../../models/model"), userModel = model.User, msg = require("../../resource/msg"), tools = require("../../util/tools"), then = require("thenjs"); exports.login = function (req, res) { var user = { loginId: req.body.loginId }; then(function (cont) { var date = Date.now(); if (!req.body.loginId) { cont(new Error(msg.USER.loginIdErr)); return; } if (!req.body.password) { cont(new Error(msg.USER.userPasswd)); return; } if (date - req.body.password > 259200000) { cont(new Error(msg.MAIN.requestOutdate)); } userModel.findOne(user).populate("group").exec(function(err, doc) { if (err) { cont(new Error(err)); return; } if (!doc) { cont(new Error(msg.USER.userNone)); return; } cont(null, doc); }); }).then(function (cont, user) { var password = req.body.password, loginId = req.body.loginId, loginTime = req.body.loginTime; if (password != tools.HmacSHA256(user.password, loginId + ":" + loginTime)) { cont(new Error(msg.USER.userPasswd)); return; } req.session.user = user; res.json({ _id: user._id, name: user.name, group: user.group, position: user.position, status: user.status, role: user.role }); }).fail(function (cont, error) { res.status(400).send(error.message); }); }; exports.logout = function (req, res) { req.session.destroy(); return res.json("success"); };
export const suffixMediaTypeMap = { 'ttl': 'text/turtle', 'trig': 'application/trig', 'jsonld': 'application/ld+json', 'xml': 'application/rdf+xml', 'rdf': 'application/rdf+xml', 'rdfs': 'application/rdf+xml', 'owl': 'application/rdf+xml', 'html': 'text/html' } export function guessMediaType (source) { let m = source ? source.match(/\.(\w+)$/) : null let suffix = m ? m[1] : 'ttl' return suffixMediaTypeMap[suffix] }
/** * main.js * * This is the entry point of the app, called from require.js */ // set some paths to import them in our modules require.config({ paths : { 'jquery' : 'libs/jquery/jquery-1.6.4.min', 'jquerymobile' : 'libs/jquery.mobile/jquery.mobile-1.0.min', 'underscore' : 'libs/underscore/underscore', // important: use backbone with AMD loading support 'backbone' : 'libs/backbone/backbone-optamd3', 'phonegap' : '../phonegap-1.2.0' } }); document.addEventListener("deviceready", function() { // start application module require([ 'app' ], function(App) { App.initialize(); }) }, true);
var pollicino = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Pollicino = undefined; 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 _qwest = __webpack_require__(1); var qwest = _interopRequireWildcard(_qwest); var _jsuri = __webpack_require__(7); var _jsuri2 = _interopRequireDefault(_jsuri); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Pollicino = function () { function Pollicino(baseUrl, appId, clientSecret) { _classCallCheck(this, Pollicino); this.baseUrl = new _jsuri2.default(baseUrl); this.appId = appId; this.clientSecret = clientSecret; this.token = null; this.requestOptions = { headers: { 'Cache-Control': '' }, dataType: 'json', responseType: 'json' }; } /* Makes a post to our url to confirm client. should get a token to be used to next requests */ _createClass(Pollicino, [{ key: "init", value: function init() { var _this = this; this.token = "123"; var authEndpoint = this.baseUrl.setPath("api/auth-client/"); return qwest.post(authEndpoint.toString(), { app_id: this.appId, client_secret: this.clientSecret }, this.requestOptions).then(function (data) { _this.token = data.response.token; //this.requestOptions.headers.Authentication = 'Token ' + this.token; _this.requestOptions.headers.Authorization = 'Token ' + _this.token; return data; }); } }, { key: "registerDevice", value: function registerDevice(deviceToken, platform) { var appVersion = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2]; console.log(3, this.requestOptions.headers); var authEndpoint = this.baseUrl.setPath("api/register-installation/"); return qwest.post(authEndpoint.toString(), { app_version: appVersion, device_token: deviceToken, platform: platform }, this.requestOptions); } /* */ }, { key: "notifyInstallation", value: function notifyInstallation(deviceId, platform) { var appVersion = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; } }]); return Pollicino; }(); exports.Pollicino = Pollicino; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /*! qwest 3.0.0 (https://github.com/pyrsmk/qwest) */ module.exports = function() { var global = window || this, pinkyswear = __webpack_require__(2), jparam = __webpack_require__(6), // Default response type for XDR in auto mode defaultXdrResponseType = 'json', // Default data type defaultDataType = 'post', // Variables for limit mechanism limit = null, requests = 0, request_stack = [], // Get XMLHttpRequest object getXHR = function(){ return global.XMLHttpRequest? new global.XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP'); }, // Guess XHR version xhr2 = (getXHR().responseType===''), // Core function qwest = function(method, url, data, options, before) { // Format method = method.toUpperCase(); data = data || null; options = options || {}; // Define variables var nativeResponseParsing = false, crossOrigin, xhr, xdr = false, timeoutInterval, aborted = false, attempts = 0, headers = {}, mimeTypes = { text: '*/*', xml: 'text/xml', json: 'application/json', post: 'application/x-www-form-urlencoded' }, accept = { text: '*/*', xml: 'application/xml; q=1.0, text/xml; q=0.8, */*; q=0.1', json: 'application/json; q=1.0, text/*; q=0.8, */*; q=0.1' }, i, j, serialized, response, sending = false, delayed = false, timeout_start, // Create the promise promise = pinkyswear(function(pinky) { pinky['catch'] = function(f) { return pinky.then(null, f); }; pinky.complete = function(f) { return pinky.then(f, f); }; // Override if('pinkyswear' in options) { for(i in options.pinkyswear) { pinky[i] = options.pinkyswear[i]; } } pinky.send = function() { // Prevent further send() calls if(sending) { return; } // Reached request limit, get out! if(requests == limit) { request_stack.push(pinky); return; } ++requests; sending = true; // Start the chrono timeout_start = new Date().getTime(); // Get XHR object xhr = getXHR(); if(crossOrigin) { if(!('withCredentials' in xhr) && global.XDomainRequest) { xhr = new XDomainRequest(); // CORS with IE8/9 xdr = true; if(method!='GET' && method!='POST') { method = 'POST'; } } } // Open connection if(xdr) { xhr.open(method, url); } else { xhr.open(method, url, options.async, options.user, options.password); if(xhr2 && options.async) { xhr.withCredentials = options.withCredentials; } } // Set headers if(!xdr) { for(var i in headers) { if(headers[i]) { xhr.setRequestHeader(i, headers[i]); } } } // Verify if the response type is supported by the current browser if(xhr2 && options.responseType!='document' && options.responseType!='auto') { // Don't verify for 'document' since we're using an internal routine try { xhr.responseType = options.responseType; nativeResponseParsing = (xhr.responseType==options.responseType); } catch(e){} } // Plug response handler if(xhr2 || xdr) { xhr.onload = handleResponse; xhr.onerror = handleError; } else { xhr.onreadystatechange = function() { if(xhr.readyState == 4) { handleResponse(); } }; } // Override mime type to ensure the response is well parsed if(options.responseType!='auto' && 'overrideMimeType' in xhr) { xhr.overrideMimeType(mimeTypes[options.responseType]); } // Run 'before' callback if(before) { before(xhr); } // Send request if(xdr) { // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ xhr.onprogress = function(){}; xhr.ontimeout = function(){}; xhr.onerror = function(){}; // https://developer.mozilla.org/en-US/docs/Web/API/XDomainRequest setTimeout(function() { xhr.send(method != 'GET'? data : null); },0); } else { xhr.send(method != 'GET' ? data : null); } }; return pinky; }), // Handle the response handleResponse = function() { // Prepare var i, responseType; --requests; sending = false; // Verify timeout state // --- https://stackoverflow.com/questions/7287706/ie-9-javascript-error-c00c023f if(new Date().getTime()-timeout_start >= options.timeout) { if(!options.attempts || ++attempts!=options.attempts) { promise.send(); } else { promise(false, [new Error('Timeout ('+url+')'), xhr, response]); } return; } // Launch next stacked request if(request_stack.length) { request_stack.shift().send(); } // Handle response try{ // Process response if(nativeResponseParsing && 'response' in xhr && xhr.response!==null) { response = xhr.response; } else if(options.responseType == 'document') { var frame = document.createElement('iframe'); frame.style.display = 'none'; document.body.appendChild(frame); frame.contentDocument.open(); frame.contentDocument.write(xhr.response); frame.contentDocument.close(); response = frame.contentDocument; document.body.removeChild(frame); } else{ // Guess response type responseType = options.responseType; if(responseType == 'auto') { if(xdr) { responseType = defaultXdrResponseType; } else { var ct = xhr.getResponseHeader('Content-Type') || ''; if(ct.indexOf(mimeTypes.json)>-1) { responseType = 'json'; } else if(ct.indexOf(mimeTypes.xml)>-1) { responseType = 'xml'; } else { responseType = 'text'; } } } // Handle response type switch(responseType) { case 'json': try { if('JSON' in global) { response = JSON.parse(xhr.responseText); } else { response = eval('('+xhr.responseText+')'); } } catch(e) { throw "Error while parsing JSON body : "+e; } break; case 'xml': // Based on jQuery's parseXML() function try { // Standard if(global.DOMParser) { response = (new DOMParser()).parseFromString(xhr.responseText,'text/xml'); } // IE<9 else { response = new ActiveXObject('Microsoft.XMLDOM'); response.async = 'false'; response.loadXML(xhr.responseText); } } catch(e) { response = undefined; } if(!response || !response.documentElement || response.getElementsByTagName('parsererror').length) { throw 'Invalid XML'; } break; default: response = xhr.responseText; } } // Late status code verification to allow passing data when, per example, a 409 is returned // --- https://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request if('status' in xhr && !/^2|1223/.test(xhr.status)) { throw xhr.status+' ('+xhr.statusText+')'; } // Fulfilled promise(true, [xhr, response]); } catch(e) { // Rejected promise(false, [e, xhr, response]); } }, // Handle errors handleError = function(e) { --requests; promise(false, [new Error('Connection aborted'), xhr, null]); }; // Normalize options options.async = 'async' in options?!!options.async:true; options.cache = 'cache' in options?!!options.cache:false; options.dataType = 'dataType' in options?options.dataType.toLowerCase():defaultDataType; options.responseType = 'responseType' in options?options.responseType.toLowerCase():'auto'; options.user = options.user || ''; options.password = options.password || ''; options.withCredentials = !!options.withCredentials; options.timeout = 'timeout' in options?parseInt(options.timeout,10):30000; options.attempts = 'attempts' in options?parseInt(options.attempts,10):1; // Guess if we're dealing with a cross-origin request i = url.match(/\/\/(.+?)\//); crossOrigin = i && (i[1]?i[1]!=location.host:false); // Prepare data if('ArrayBuffer' in global && data instanceof ArrayBuffer) { options.dataType = 'arraybuffer'; } else if('Blob' in global && data instanceof Blob) { options.dataType = 'blob'; } else if('Document' in global && data instanceof Document) { options.dataType = 'document'; } else if('FormData' in global && data instanceof FormData) { options.dataType = 'formdata'; } switch(options.dataType) { case 'json': data = (data !== null ? JSON.stringify(data) : data); break; case 'post': data = jparam(data); } // Prepare headers if(options.headers) { var format = function(match,p1,p2) { return p1 + p2.toUpperCase(); }; for(i in options.headers) { headers[i.replace(/(^|-)([^-])/g,format)] = options.headers[i]; } } if(!('Content-Type' in headers) && method!='GET') { if(options.dataType in mimeTypes) { if(mimeTypes[options.dataType]) { headers['Content-Type'] = mimeTypes[options.dataType]; } } } if(!headers.Accept) { headers.Accept = (options.responseType in accept)?accept[options.responseType]:'*/*'; } if(!crossOrigin && !('X-Requested-With' in headers)) { // (that header breaks in legacy browsers with CORS) headers['X-Requested-With'] = 'XMLHttpRequest'; } if(!options.cache && !('Cache-Control' in headers)) { headers['Cache-Control'] = 'no-cache'; } // Prepare URL if(method == 'GET' && data && typeof data == 'string') { url += (/\?/.test(url)?'&':'?') + data; } // Start the request if(options.async) { promise.send(); } // Return promise return promise; }; // Return the external qwest object return { base: '', get: function(url, data, options, before) { return qwest('GET', this.base+url, data, options, before); }, post: function(url, data, options, before) { return qwest('POST', this.base+url, data, options, before); }, put: function(url, data, options, before) { return qwest('PUT', this.base+url, data, options, before); }, 'delete': function(url, data, options, before) { return qwest('DELETE', this.base+url, data, options, before); }, map: function(type, url, data, options, before) { return qwest(type.toUpperCase(), this.base+url, data, options, before); }, xhr2: xhr2, limit: function(by) { limit = by; }, setDefaultXdrResponseType: function(type) { defaultXdrResponseType = type.toLowerCase(); }, setDefaultDataType: function(type) { defaultDataType = type.toLowerCase(); } }; }(); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, setImmediate, process) {/* * PinkySwear.js 2.2.2 - Minimalistic implementation of the Promises/A+ spec * * Public Domain. Use, modify and distribute it any way you like. No attribution required. * * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. * * PinkySwear is a very small implementation of the Promises/A+ specification. After compilation with the * Google Closure Compiler and gzipping it weighs less than 500 bytes. It is based on the implementation for * Minified.js and should be perfect for embedding. * * * PinkySwear has just three functions. * * To create a new promise in pending state, call pinkySwear(): * var promise = pinkySwear(); * * The returned object has a Promises/A+ compatible then() implementation: * promise.then(function(value) { alert("Success!"); }, function(value) { alert("Failure!"); }); * * * The promise returned by pinkySwear() is a function. To fulfill the promise, call the function with true as first argument and * an optional array of values to pass to the then() handler. By putting more than one value in the array, you can pass more than one * value to the then() handlers. Here an example to fulfill a promsise, this time with only one argument: * promise(true, [42]); * * When the promise has been rejected, call it with false. Again, there may be more than one argument for the then() handler: * promise(true, [6, 6, 6]); * * You can obtain the promise's current state by calling the function without arguments. It will be true if fulfilled, * false if rejected, and otherwise undefined. * var state = promise(); * * https://github.com/timjansen/PinkySwear.js */ (function(target) { var undef; function isFunction(f) { return typeof f == 'function'; } function isObject(f) { return typeof f == 'object'; } function defer(callback) { if (typeof setImmediate != 'undefined') setImmediate(callback); else if (typeof process != 'undefined' && process['nextTick']) process['nextTick'](callback); else setTimeout(callback, 0); } target[0][target[1]] = function pinkySwear(extend) { var state; // undefined/null = pending, true = fulfilled, false = rejected var values = []; // an array of values as arguments for the then() handlers var deferred = []; // functions to call when set() is invoked var set = function(newState, newValues) { if (state == null && newState != null) { state = newState; values = newValues; if (deferred.length) defer(function() { for (var i = 0; i < deferred.length; i++) deferred[i](); }); } return state; }; set['then'] = function (onFulfilled, onRejected) { var promise2 = pinkySwear(extend); var callCallbacks = function() { try { var f = (state ? onFulfilled : onRejected); if (isFunction(f)) { function resolve(x) { var then, cbCalled = 0; try { if (x && (isObject(x) || isFunction(x)) && isFunction(then = x['then'])) { if (x === promise2) throw new TypeError(); then['call'](x, function() { if (!cbCalled++) resolve.apply(undef,arguments); } , function(value){ if (!cbCalled++) promise2(false,[value]);}); } else promise2(true, arguments); } catch(e) { if (!cbCalled++) promise2(false, [e]); } } resolve(f.apply(undef, values || [])); } else promise2(state, values); } catch (e) { promise2(false, [e]); } }; if (state != null) defer(callCallbacks); else deferred.push(callCallbacks); return promise2; }; if(extend){ set = extend(set); } return set; }; })( false ? [window, 'pinkySwear'] : [module, 'exports']); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)(module), __webpack_require__(4).setImmediate, __webpack_require__(5))) /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var nextTick = __webpack_require__(5).nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { if (immediateIds[id]) { // fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu if (args) { fn.apply(null, args); } else { fn.call(null); } // Prevent ids from leaking exports.clearImmediate(id); } }); return id; }; exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { delete immediateIds[id]; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4).setImmediate, __webpack_require__(4).clearImmediate)) /***/ }, /* 5 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** * @preserve jquery-param (c) 2015 KNOWLEDGECODE | MIT */ /*global define */ (function (global) { 'use strict'; var param = function (a) { var add = function (s, k, v) { v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v; s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v); }, buildParams = function (prefix, obj, s) { var i, len, key; if (Object.prototype.toString.call(obj) === '[object Array]') { for (i = 0, len = obj.length; i < len; i++) { buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i], s); } } else if (obj && obj.toString() === '[object Object]') { for (key in obj) { if (obj.hasOwnProperty(key)) { if (prefix) { buildParams(prefix + '[' + key + ']', obj[key], s, add); } else { buildParams(key, obj[key], s, add); } } } } else if (prefix) { add(s, prefix, obj); } else { for (key in obj) { add(s, key, obj[key]); } } return s; }; return buildParams('', a, []).join('&').replace(/%20/g, '+'); }; if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = param; } else if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return param; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { global.param = param; } }(this)); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * jsUri * https://github.com/derek-watson/jsUri * * Copyright 2013, Derek Watson * Released under the MIT license. * * Includes parseUri regular expressions * http://blog.stevenlevithan.com/archives/parseuri * Copyright 2007, Steven Levithan * Released under the MIT license. */ /*globals define, module */ (function(global) { var re = { starts_with_slashes: /^\/+/, ends_with_slashes: /\/+$/, pluses: /\+/g, query_separator: /[&;]/, uri_parser: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*)(?::([^:@]*))?)?@)?(\[[0-9a-fA-F:.]+\]|[^:\/?#]*)(?::(\d+|(?=:)))?(:)?)((((?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ }; /** * Define forEach for older js environments * @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach#Compatibility */ if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this == null) { throw new TypeError(' this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } /** * unescape a query param value * @param {string} s encoded value * @return {string} decoded value */ function decode(s) { if (s) { s = s.toString().replace(re.pluses, '%20'); s = decodeURIComponent(s); } return s; } /** * Breaks a uri string down into its individual parts * @param {string} str uri * @return {object} parts */ function parseUri(str) { var parser = re.uri_parser; var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"]; var m = parser.exec(str || ''); var parts = {}; parserKeys.forEach(function(key, i) { parts[key] = m[i] || ''; }); return parts; } /** * Breaks a query string down into an array of key/value pairs * @param {string} str query * @return {array} array of arrays (key/value pairs) */ function parseQuery(str) { var i, ps, p, n, k, v, l; var pairs = []; if (typeof(str) === 'undefined' || str === null || str === '') { return pairs; } if (str.indexOf('?') === 0) { str = str.substring(1); } ps = str.toString().split(re.query_separator); for (i = 0, l = ps.length; i < l; i++) { p = ps[i]; n = p.indexOf('='); if (n !== 0) { k = decode(p.substring(0, n)); v = decode(p.substring(n + 1)); pairs.push(n === -1 ? [p, null] : [k, v]); } } return pairs; } /** * Creates a new Uri object * @constructor * @param {string} str */ function Uri(str) { this.uriParts = parseUri(str); this.queryPairs = parseQuery(this.uriParts.query); this.hasAuthorityPrefixUserPref = null; } /** * Define getter/setter methods */ ['protocol', 'userInfo', 'host', 'port', 'path', 'anchor'].forEach(function(key) { Uri.prototype[key] = function(val) { if (typeof val !== 'undefined') { this.uriParts[key] = val; } return this.uriParts[key]; }; }); /** * if there is no protocol, the leading // can be enabled or disabled * @param {Boolean} val * @return {Boolean} */ Uri.prototype.hasAuthorityPrefix = function(val) { if (typeof val !== 'undefined') { this.hasAuthorityPrefixUserPref = val; } if (this.hasAuthorityPrefixUserPref === null) { return (this.uriParts.source.indexOf('//') !== -1); } else { return this.hasAuthorityPrefixUserPref; } }; Uri.prototype.isColonUri = function (val) { if (typeof val !== 'undefined') { this.uriParts.isColonUri = !!val; } else { return !!this.uriParts.isColonUri; } }; /** * Serializes the internal state of the query pairs * @param {string} [val] set a new query string * @return {string} query string */ Uri.prototype.query = function(val) { var s = '', i, param, l; if (typeof val !== 'undefined') { this.queryPairs = parseQuery(val); } for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; if (s.length > 0) { s += '&'; } if (param[1] === null) { s += param[0]; } else { s += param[0]; s += '='; if (typeof param[1] !== 'undefined') { s += encodeURIComponent(param[1]); } } } return s.length > 0 ? '?' + s : s; }; /** * returns the first query param value found for the key * @param {string} key query key * @return {string} first value found for key */ Uri.prototype.getQueryParamValue = function (key) { var param, i, l; for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; if (key === param[0]) { return param[1]; } } }; /** * returns an array of query param values for the key * @param {string} key query key * @return {array} array of values */ Uri.prototype.getQueryParamValues = function (key) { var arr = [], i, param, l; for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; if (key === param[0]) { arr.push(param[1]); } } return arr; }; /** * removes query parameters * @param {string} key remove values for key * @param {val} [val] remove a specific value, otherwise removes all * @return {Uri} returns self for fluent chaining */ Uri.prototype.deleteQueryParam = function (key, val) { var arr = [], i, param, keyMatchesFilter, valMatchesFilter, l; for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; keyMatchesFilter = decode(param[0]) === decode(key); valMatchesFilter = param[1] === val; if ((arguments.length === 1 && !keyMatchesFilter) || (arguments.length === 2 && (!keyMatchesFilter || !valMatchesFilter))) { arr.push(param); } } this.queryPairs = arr; return this; }; /** * adds a query parameter * @param {string} key add values for key * @param {string} val value to add * @param {integer} [index] specific index to add the value at * @return {Uri} returns self for fluent chaining */ Uri.prototype.addQueryParam = function (key, val, index) { if (arguments.length === 3 && index !== -1) { index = Math.min(index, this.queryPairs.length); this.queryPairs.splice(index, 0, [key, val]); } else if (arguments.length > 0) { this.queryPairs.push([key, val]); } return this; }; /** * test for the existence of a query parameter * @param {string} key add values for key * @param {string} val value to add * @param {integer} [index] specific index to add the value at * @return {Uri} returns self for fluent chaining */ Uri.prototype.hasQueryParam = function (key) { var i, len = this.queryPairs.length; for (i = 0; i < len; i++) { if (this.queryPairs[i][0] == key) return true; } return false; }; /** * replaces query param values * @param {string} key key to replace value for * @param {string} newVal new value * @param {string} [oldVal] replace only one specific value (otherwise replaces all) * @return {Uri} returns self for fluent chaining */ Uri.prototype.replaceQueryParam = function (key, newVal, oldVal) { var index = -1, len = this.queryPairs.length, i, param; if (arguments.length === 3) { for (i = 0; i < len; i++) { param = this.queryPairs[i]; if (decode(param[0]) === decode(key) && decodeURIComponent(param[1]) === decode(oldVal)) { index = i; break; } } if (index >= 0) { this.deleteQueryParam(key, decode(oldVal)).addQueryParam(key, newVal, index); } } else { for (i = 0; i < len; i++) { param = this.queryPairs[i]; if (decode(param[0]) === decode(key)) { index = i; break; } } this.deleteQueryParam(key); this.addQueryParam(key, newVal, index); } return this; }; /** * Define fluent setter methods (setProtocol, setHasAuthorityPrefix, etc) */ ['protocol', 'hasAuthorityPrefix', 'isColonUri', 'userInfo', 'host', 'port', 'path', 'query', 'anchor'].forEach(function(key) { var method = 'set' + key.charAt(0).toUpperCase() + key.slice(1); Uri.prototype[method] = function(val) { this[key](val); return this; }; }); /** * Scheme name, colon and doubleslash, as required * @return {string} http:// or possibly just // */ Uri.prototype.scheme = function() { var s = ''; if (this.protocol()) { s += this.protocol(); if (this.protocol().indexOf(':') !== this.protocol().length - 1) { s += ':'; } s += '//'; } else { if (this.hasAuthorityPrefix() && this.host()) { s += '//'; } } return s; }; /** * Same as Mozilla nsIURI.prePath * @return {string} scheme://user:password@host:port * @see https://developer.mozilla.org/en/nsIURI */ Uri.prototype.origin = function() { var s = this.scheme(); if (this.userInfo() && this.host()) { s += this.userInfo(); if (this.userInfo().indexOf('@') !== this.userInfo().length - 1) { s += '@'; } } if (this.host()) { s += this.host(); if (this.port() || (this.path() && this.path().substr(0, 1).match(/[0-9]/))) { s += ':' + this.port(); } } return s; }; /** * Adds a trailing slash to the path */ Uri.prototype.addTrailingSlash = function() { var path = this.path() || ''; if (path.substr(-1) !== '/') { this.path(path + '/'); } return this; }; /** * Serializes the internal state of the Uri object * @return {string} */ Uri.prototype.toString = function() { var path, s = this.origin(); if (this.isColonUri()) { if (this.path()) { s += ':'+this.path(); } } else if (this.path()) { path = this.path(); if (!(re.ends_with_slashes.test(s) || re.starts_with_slashes.test(path))) { s += '/'; } else { if (s) { s.replace(re.ends_with_slashes, '/'); } path = path.replace(re.starts_with_slashes, '/'); } s += path; } else { if (this.host() && (this.query().toString() || this.anchor())) { s += '/'; } } if (this.query().toString()) { s += this.query().toString(); } if (this.anchor()) { if (this.anchor().indexOf('#') !== 0) { s += '#'; } s += this.anchor(); } return s; }; /** * Clone a Uri object * @return {Uri} duplicate copy of the Uri */ Uri.prototype.clone = function() { return new Uri(this.toString()); }; /** * export via AMD or CommonJS, otherwise leak a global */ if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return Uri; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = Uri; } else { global.Uri = Uri; } }(this)); /***/ } /******/ ]);
define([ 'intern!object', 'intern/chai!assert', 'oe_dojo/TrackableMemoryStore' ], function ( registerSuite, assert, TrackableMemoryStore ) { var tmStore; registerSuite({ name: 'TrackableMemoryStore', setup: function() { tmStore = new TrackableMemoryStore({data: []}); }, 'trackable store': function() { assert.isFunction(tmStore.track, 'TrackableMemoryStore should have a track() function'); }, 'memory store': function() { assert.isFunction(tmStore.getSync, 'TrackableMemoryStore should have a get() function'); assert.isFunction(tmStore.addSync, 'TrackableMemoryStore should have a add() function'); assert.isFunction(tmStore.removeSync, 'TrackableMemoryStore should have a remove() function'); assert.isFunction(tmStore.putSync, 'TrackableMemoryStore should have a put() function'); } }); });
// artist.model.js //============================================== //====== Define depencies ====== const mongoose = require('mongoose'), utils = require('../../utils/utils'), Schema = mongoose.Schema; //====== Define schema ====== const artistSchema = new Schema({ name: { type: String, required: true }, slug: { type: String, unique: true }, location: { city: { type: String, required: true }, coordinates: String, neighborhood: String, _id : false }, categories: Array, image: { thumbnailUrl: String, _id : false }, bio: { summary: String, url: String, birthdate: Date, deathdate: Date, yearsActiveStart: Number, yearsActiveEnd: Number, _id : false }, youtube: { clipExampleUrl: String, _id : false }, createDate: { type: Date, default: Date.now }, published: { type: Boolean, default: false } }, { minimize: false }); //====== Middleware ====== artistSchema.pre('save', function(next) { this.slug = utils.slugify(this.name); next(); }); // Handler **must** take 3 parameters: the error that occurred, the document // in question, and the `next()` function artistSchema.post('save', function(error, req, next) { if (error.name === 'MongoError' && error.code === 11000) { next(new utils.JsonError(`Artist ${this.name} already exists`, 'name', this.name)); } else { next(error); } }); //====== Export the model ====== module.exports = mongoose.model('Artist', artistSchema);
module.exports = require("npm:togeojson@0.13.0/togeojson.js");
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; import red from '@material-ui/core/colors/red'; export const cofactsColors = { red1: '#fb5959', red2: '#ff7b7b', orange1: '#ff8a00', orange2: '#ffb600', yellow: '#ffea29', green1: '#00b172', green2: '#00d88b', green3: '#4ff795', blue1: '#2079f0', blue2: '#2daef7', blue3: '#5fd8ff', purple: '#966dee', }; const baseThemeOption = { palette: { primary: { main: '#ffb600', 50: '#fff890', 100: '#fff000', 200: '#ffe200', 300: '#ffd300', 400: '#ffc500', 500: '#ffb600', 600: '#ffa300', 700: '#ff9200', 800: '#ff7f00', 900: '#ff6d00', }, secondary: { main: '#333333', 50: '#f5f5f5', 100: '#d6d6d6', 200: '#adadad', 300: '#858585', 400: '#5c5c5c', 500: '#333333', 600: '#2e2e2e', 700: '#292929', 800: '#242424', 900: '#1f1f1f', }, error: { main: red.A400, }, background: { default: '#f5f5f5', }, common: cofactsColors, }, typography: { // Avoid flicker on devices that has Noto Sans installed fontFamily: '"Noto Sans TC", "Noto Sans CJK TC", "Source Han Sans", "ๆ€ๆบ้ป‘้ซ”", sans-serif', }, shape: { borderRadius: 8, }, }; // Create a theme instance. export const lightTheme = createMuiTheme(baseThemeOption); export const darkTheme = createMuiTheme({ ...baseThemeOption, palette: { ...baseThemeOption.palette, type: 'dark', background: { default: '#2e2e2e', paper: '#333', }, }, }); export function withDarkTheme(WrappedComponent) { function Component(props) { return ( <ThemeProvider theme={darkTheme}> <WrappedComponent {...props} /> </ThemeProvider> ); } const componentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; Component.displayName = `withDarkTheme(${componentName})`; return Component; }
'use strict'; var React = require('react/addons'); module.exports = { propTypes: { size: React.PropTypes.number, className: React.PropTypes.string }, getDefaultProps: function() { return { size: 48, className: "reacticon" }; }, render: function() { return ( <svg version="1.1" width={this.props.size + 'px'} height={this.props.size + 'px'} className={this.props.className} viewBox="0 0 48 48"> {this.renderGraphic(this.props.type)} </svg> ); } };
export { default } from 'ember-flexberry-gis/helpers/regex-test';
'use strict'; const React = require('react'); const client = require('./client'); class App extends React.Component { constructor(props) { super(props); this.state = {users: []}; } componentDidMount() { client({method: 'GET', path: '/api/users'}).done(response => { this.setState({users: response.entity._embedded.users}); }); } render() { return ( <UserList users={this.state.users}/> ) } } class UserList extends React.Component{ render() { var users = this.props.users.map(user => <User key={user._links.self.href} user={user}/> ); return ( <table> <tr> <th>Name</th> <th>E-Mail</th> <th>Sex</th> </tr> {users} </table> ) } } class User extends React.Component{ render() { return ( <tr> <td>{this.props.user.name}</td> <td>{this.props.user.email}</td> <td>{this.props.user.sex}</td> </tr> ) } } React.render( <App />, document.getElementById('react') )
/** * Promised models */ var Events = require('./events'), Vow = require('vow'), uniq = require('./uniq'), IdAttribute = require('./types/id'), Attribute = require('./attribute'), fulfill = require('./fulfill'), /** * @class Model * @extends Events */ Model = Events.inherit(/** @lends Model.prototype */{ /** * @deprecated use getId method */ id: null, CALCULATIONS_BRANCH: 'CALCULATIONS_BRANCH', /** * @param {*} [id] * @param {Object} [data] initial data * @param {Object} [options] */ __constructor: function (data, options) { var Storage, i, n, attrName, Attribute, modelAttrsDecl; this.__base(); options = options === undefined ? {} : options; this.CHANGE_BRANCH = uniq(); Storage = options.storage || this.storage; if (options.collection) { this.collection = options.collection; } this._isNested = Boolean(options.isNested); this._ready = true; this._readyPromise = fulfill(); this.storage = Storage ? new Storage() : null; this._attributesNames = Object.keys(this.attributes || {}); modelAttrsDecl = this.attributes; this.attributes = {}; for (i = 0, n = this._attributesNames.length; i < n; i++) { attrName = this._attributesNames[i]; Attribute = modelAttrsDecl[attrName]; this.attributes[attrName] = new Attribute(attrName, this, (data || {})[attrName]); if (this.attributes[attrName] instanceof IdAttribute) { this.idAttribute = this.attributes[attrName]; } } this.commit(this.CHANGE_BRANCH); this.calculate(); }, /** * @returns {*} */ getId: function () { return this.idAttribute ? this.idAttribute.get() : null; }, /** * set attribute to default value * @param {string} attributeName */ unset: function (attributeName) { this._throwMissedAttribute(attributeName); this.attributes[attributeName].unset(); }, /** * check if attribute was set * @param {string} attributeName * @return {Boolean} */ isSet: function (attributeName) { this._throwMissedAttribute(attributeName); return this.attributes[attributeName].isSet(); }, /** * when false calculation errors will be silent * @type {Boolean} */ throwCalculationErrors: true, /** * if model was synced with storage * @return {Boolean} */ isNew: function () { return this.getId() === null; }, /** * Returns true if model was created by another model or collection * @returns {Boolean} */ isNested: function () { return this._isNested; }, /** * save model changes * @return {Promise} */ save: function () { var model = this; if (!model.idAttribute) { throw new Error('model without declared perisitent id attribute cat not be saved'); } return this._rejectDestructed().then(function () { if (model.isNew()) { return model.ready().then(function () { return model.storage.insert(model); }).then(function (id) { model.idAttribute.set(id); model.commit(); model.calculate(); return model.ready(); }); } else { return model.ready().then(function () { return model.storage.update(model); }).then(function () { model.commit(); }); } }); }, /** * fetch model from storage * @return {Promise} */ fetch: function () { var model = this; if (!model.idAttribute) { throw new Error('model can not be fetched from persistent storage, if it has no persistent id'); } return this.ready().then(function () { return model.storage.find(model); }).then(function (data) { model.set(data); return model.ready(); }).then(function () { model.commit(); }); }, /** * remove model from storage and destruct it * @return {Promise} */ remove: function () { var model = this; if (model.isNew()) { model.destruct(); return fulfill(); } else { if (!model.idAttribute) { throw new Error('model can not be removed from persistet storage, if it has no persistent id'); } return fulfill().then(function () { return model.storage.remove(model); }).then(function () { model.destruct(); }); } }, /** * check of model destruted * @return {Boolean} */ isDestructed: function () { return Boolean(this._isDestructed); }, /** * destruct model instance */ destruct: function () { this._isDestructed = true; this.trigger('destruct'); this._eventEmitter.removeAllListeners(); this.eachAttribute(function (attribute) { attribute.destruct(); }); }, /** * @param {Function} cb * @param {Object} [ctx] */ eachAttribute: function (cb, ctx) { this._attributesNames.forEach(function (attrName) { if (ctx) { cb.call(ctx, this.attributes[attrName]); } else { cb(this.attributes[attrName]); } }, this); }, /** * check if model is valid * @return {Promise<Boolean, Model.ValidationError>} */ validate: function () { var model = this; return model.ready().then(function () { return Vow.allResolved(model._attributesNames.map(function (attrName) { return model.attributes[attrName].validate(); })); }).then(function (validationPromises) { var errors = [], error; validationPromises.forEach(function (validationPromise, index) { var validationResult, error; if (validationPromise.isFulfilled()) { return; } validationResult = validationPromise.valueOf(); if (validationResult instanceof Error) { error = validationResult; } else { error = new Attribute.ValidationError(); if (typeof validationResult === 'string') { error.message = validationResult; } else if (typeof validationResult !== 'boolean') { error.data = validationResult; } } error.attribute = model.attributes[model._attributesNames[index]]; errors.push(error); }); if (errors.length) { error = new model.__self.ValidationError(); error.attributes = errors; return Vow.reject(error); } else { return fulfill(true); } }); }, /** * check if any attribute is changed * @prop {string} [branch=DEFAULT_BRANCH] * @return {Boolean} */ isChanged: function (branch) { return this._attributesNames.some(function (attrName) { return this.attributes[attrName].isChanged(branch); }, this); }, /** * revert all attributes to initial or last commited value * @prop {string} [branch=DEFAULT_BRANCH] */ revert: function (branch) { this.eachAttribute(function (attr) { attr.revert(branch); }); }, /** * commit current value, to not be rolled back * @prop {string} [branch=DEFAULT_BRANCH] * @return {boolean} */ commit: function (branch) { var eventString, changed = false; this.eachAttribute(function (attr) { changed = attr.commit(branch) || changed; }); if (changed) { eventString = (branch ? branch + ':' : '') + 'commit'; this.trigger(eventString); } return changed; }, /** * @param {string} [branch=DEFAULT_BRANCH] * @returns {Object} */ getLastCommitted: function (branch) { return this._getSerializedData('getLastCommitted', branch); }, /** * @param {String} [attr] - if not defined returns all attributes * @returns {*} */ previous: function (attr) { if (arguments.length) { return this.attributes[attr].previous(); } else { return this._getSerializedData('previous'); } }, /** * set attribute value * @param {string|object} name or data * @param {*} value * @return {Boolean} if attribute found */ set: function (name, value) { var data; if (arguments.length === 1) { data = name; this._attributesNames.forEach(function (name) { if (data[name] !== undefined) { this.set(name, data[name]); } }, this); } else if (this.attributes[name]) { this.attributes[name].set(value); } return this; }, /** * get attribute valie * @param {string} attributeName * @return {*} */ get: function (attributeName) { this._throwMissedAttribute(attributeName); return this.attributes[attributeName].get(); }, /** * return model data * @return {object} */ toJSON: function () { return this._getSerializedData('toJSON'); }, /** * if all calculations are done * @return {Boolean} */ isReady: function () { return this._ready; }, /** * wait for all calculations to be done * @return {Promise} */ ready: function () { return this._readyPromise; }, /** * make all calculations for attributes * @return {Promise} */ calculate: function () { var model = this; if (this.isReady()) { this._ready = false; this.trigger('calculate'); //start _calculate on next tick this._readyPromise = fulfill().then(function () { return model._calculate(); }); this._readyPromise.fail(function (e) { console.error(e, e && e.stack); model._ready = true; }); } else { this._requireMoreCalculations = true; } if (this.throwCalculationErrors) { return this._readyPromise; } else { return this._readyPromise.always(function () { return fulfill(); }); } }, /** * @returns {Model} */ trigger: function (event, a1, a2) { switch (arguments.length) { case 1: return this.__base(event, this); case 2: return this.__base(event, this, a1); case 3: return this.__base(event, this, a1, a2); } }, /** * to prevent loop calculations we limit it * @type {Number} */ maxCalculations: 100, /** * marker that requires one more calculation cycle * @type {Boolean} */ _requireMoreCalculations: false, /** * @param {Number} [n = 0] itteration * @return {Promise} */ _calculate: function (n) { var model = this, calculations = {}, hasCalculations = false, promises = [], amendings = [], nestedCalculations = []; n = n || 0; this._requireMoreCalculations = false; this._ready = false; if (n >= this.maxCalculations) { return this._throwCalculationLoop(); } this._requireMoreCalculations = false; this.commit(this.CALCULATIONS_BRANCH); this.eachAttribute(function (attribute) { var calculationResult, amendResult, nestedResult; if (attribute.calculate) { calculationResult = attribute.calculate(); calculations[attribute.name] = attribute.calculate(); hasCalculations = true; } if (attribute.amend && attribute.isChanged(model.CHANGE_BRANCH)) { amendResult = attribute.amend(); if (Vow.isPromise(amendResult) && !amendResult.isResolved()) { promises.push(amendResult); } } if (attribute.ready) { nestedResult = attribute.ready(); if (Vow.isPromise(nestedResult) && !nestedResult.isResolved()) { promises.push(nestedResult); } } }); if (hasCalculations || promises.length) { return Vow.all([ Vow.all(calculations), Vow.all(promises) ]).spread(this._onCalculateSuccess.bind(this, n)); } else { return this._onCalculateSuccess(n); } }, /** * @param {Number} n * @param {Object} [calculateData] * @returns {?Vow.Promise} */ _onCalculateSuccess: function (n, calculateData) { if (!this._setCalculatedData(calculateData) || this._checkContinueCalculations()) { return this._calculate(++n); } else { this._triggerEvents(); //some event habdler could change some attribute if (this._checkContinueCalculations()) { return this._calculate(++n); } } this._ready = true; }, /** * setting calculated data only if nothing have changed during calculations * otherwise we will have racing conditions( * @param {object} calculateData */ _setCalculatedData: function (calculateData) { if (!this._checkContinueCalculations()) { calculateData && this.set(calculateData); return true; } }, _checkContinueCalculations: function () { return this.isChanged(this.CALCULATIONS_BRANCH) || this._requireMoreCalculations; }, /** * @return {Promise<, {Error}>} rejected promise */ _throwCalculationLoop: function () { var changedFields = this._attributesNames.filter(function (attrName) { return this.attributes[attrName].isChanged(this.CALCULATIONS_BRANCH); }, this); return Vow.reject(new Error( 'After ' + this.maxCalculations + ' calculations fileds ' + changedFields + ' still changed' )); }, _triggerEvents: function () { var changedFileds; if (this.isChanged(this.CHANGE_BRANCH)) { changedFileds = this._attributesNames.filter(function (attrName) { return this.attributes[attrName].isChanged(this.CHANGE_BRANCH); }, this); this.commit(this.CHANGE_BRANCH); changedFileds.forEach(function (attrName) { this._emitAttributeChange(this.attributes[attrName]); }, this); this._emitChange(); } }, /** * @param {Model.Attribute} attribute */ _emitAttributeChange: function (attribute) { this.trigger('change:' + attribute.name); }, _emitChange: function () { this.trigger('change'); }, /** * @return {Promise} */ _rejectDestructed: function () { if (this.isDestructed()) { return Vow.reject(new Error ('Model is destructed')); } else { return fulfill(); } }, _throwMissedAttribute: function (attributeName) { if (!this.attributes[attributeName]) { throw new Error('Unknown attribute ' + attributeName); } }, /** * @param {('toJSON'|'getLastCommitted'|'previous')} serializeMethod * @param {...*} [args] * @returns {Object} */ _getSerializedData: function (serializeMethod, a) { var data = {}; this.eachAttribute(function (attribute) { if (!attribute.internal) { data[attribute.name] = attribute[serializeMethod](a); } }, this); return data; } }, { /** * @override */ inherit: function (props, staticProps) { staticProps = staticProps || {}; staticProps.attributes = staticProps.attributes || props.attributes; staticProps.storage = staticProps.storage || props.storage; return this.__base(props, staticProps); }, /** * @class * @abstract */ Storage: require('./storage'), attributeTypes: { Id: IdAttribute, String: require('./types/string'), Number: require('./types/number'), Boolean: require('./types/boolean'), List: require('./types/list'), Model: require('./types/model'), ModelsList: require('./types/models-list'), Collection: require('./types/collection'), Object: require('./types/object'), Raw: require('./types/raw') }, /** * @type {Attribute} * @prop {*} [initValue] */ Attribute: require('./attribute'), Collection: require('./collection'), /** * @class <{Error}> * @prop {Array<{Attribute}>} attributes */ ValidationError: (function () { var ValidationError = function () { this.name = 'ValidationError'; this.attributes = []; Error.call(this); //super constructor if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = (new Error()).stack; } }; ValidationError.prototype = Object.create(Error.prototype); ValidationError.prototype.constructor = ValidationError; return ValidationError; }()) }); module.exports = Model;
/* jshint node: true, quotmark: false */ /*global suite, test */ 'use strict'; var lib = { assert: require('assert'), fs: require('fs'), url: require('url'), nock: require('nock'), letatlin: require('../'), mockfs: require('mock-fs') }; var assert = lib.assert; var etcd = lib.nock('http://127.0.0.1:4001'); etcd.get('/v2/keys/letatlin-test/plain?recursive=false') .reply(200, {"action":"get","node":{"key":"/letatlin-test/plain","value":"plain value","modifiedIndex":79318,"createdIndex":79318}}, { 'content-type': 'application/json', 'x-etcd-index': '79326', 'x-raft-index': '943394', 'x-raft-term': '15', date: 'Tue, 29 Jul 2014 11:34:25 GMT', 'transfer-encoding': 'chunked' }); etcd.get('/v2/keys/letatlin-test/plain?recursive=false').reply(500, {}); suite('Persist and fall back', function testLoadingAllTypes() { var options = { persistPath: 'mock/environment.config.json', logger: function() {}, }; var config = { plain: {key:'/letatlin-test/plain'} }; test('Persist', function testPersist(done) { lib.mockfs({ 'mock': {}, }); lib.letatlin(config, options, function loadResult(error) { if (error) { lib.mockfs.restore(); assert.ifError(error); } var persisted = lib.fs.readFileSync(options.persistPath, {encoding:'utf8'}); lib.mockfs.restore(); assert.equal(persisted, JSON.stringify({ "/letatlin-test/plain": "plain value" }, null, ' ')); done(); }); }); test('Fall back', function testFallback(done) { lib.mockfs({ 'mock/environment.config.json': '{"/letatlin-test/plain": "fallback value"}', }); lib.letatlin(config, options, function loadResult(error, values) { lib.mockfs.restore(); assert.ifError(error); assert.deepEqual(values, {"plain": "fallback value"}); done(); }); }); });
/* The store of the Sorter. Not needed at the moment */ export default class SorterStore { constructor() { this.AppActions = this.alt.getActions('AppActions'); this.bindActions(this.AppActions); } }
var ID = { CONTAINER : 'ATT-trello-container', IFRAME_PREFIX : 'iheart-iframe-' }; var _this = {}, _views = {}, _container = null; if ($('#'+ID.CONTAINER).length > 0) { _container = $('#'+ID.CONTAINER) _container.show(); } else { _container = $('<div />', {id:ID.CONTAINER}); _container.appendTo(document.body); getView('trello', _container); } // private functions -------------------------------------------------------- function getView (id){ // This function is originally from https://github.com/ffto/iHeart-Chrome-Extension // return the view if it's already created if (_views[id]) return _views[id]; // iframe initial details var src = chrome.extension.getURL('html/frame/'+id+'.html?view='+id+'&_'+(new Date().getTime())), iframe = $('<iframe />', {id:ID.IFRAME_PREFIX+id, src:src, scrolling:false}); // view _views[id] = { isLoaded : false, iframe : iframe }; // add to the container _container.append(iframe); return _views[id]; }; // Handle message from frame addEventListener('message', function(ev) { switch (ev.data.message) { case 'ATTcloseIframe': ATTcloseModal(); break; case 'ATTaddTrello': add2Trello(ev.data.data); // $('#ATT-trello-container').fadeOut(); ATTcloseModal(); break; } }); // handle message from background js chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { switch (request.ATTaction) { case 'exist': sendResponse({message: "yeap"}); break; case 'showTime': alert('showTime'); break; } }); // Close modal function ATTcloseModal(){ $('#ATT-trello-container').fadeOut(); } function add2Trello(data){ alert('log'); console.log(data); chrome.extension.sendRequest({action: "ATTaddTrello", data: data, url: window.location.href}); } // Utils var contentScript = { // Adapted from: http://www.sitepoint.com/chrome-extensions-bridging-the-gap-between-layers/ tellBackGround: function(message, data){ var data = data || {}; // send a message to "background.js" chrome.extension.sendRequest({ message : message, data : data }); } }
import * as usersService from '../services/IndexPage'; export default { namespace: 'message', state: {}, reducers: { receiveMessage(state, { payload: { hasReadMessage, hasNotReadMessage } }) { return { ...state, hasReadMessage, hasNotReadMessage }; }, }, effects: { *fetchMessage({ payload: accessToken }, { put, call }) { const { data } = yield call(usersService.fetchMessage, accessToken); yield put({ type: 'receiveMessage', payload: { hasReadMessage: data.data.has_read_messages, hasNotReadMessage: data.data.hasnot_read_messages, }, }); }, }, subscriptions: {}, };
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright ยฉ 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable max-len */ if (process.env.BROWSER) { throw new Error('Do not import `config.js` from inside the client-side code.'); } module.exports = { // default locale is the first one locales: ['uk-UA', 'ru-RU'], // Node.js app port: process.env.PORT || 3000, // API Gateway api: { // API URL to be used in the client-side code clientUrl: process.env.API_CLIENT_URL || '', // API URL to be used in the server-side code serverUrl: process.env.API_SERVER_URL || `http://localhost:${process.env.PORT || 3000}`, }, // Database databaseUrl: process.env.DATABASE_URL || 'sqlite:database.sqlite', // Web analytics analytics: { // https://analytics.google.com/ googleTrackingId: process.env.GOOGLE_TRACKING_ID, // UA-XXXXX-X }, // Authentication auth: { jwt: { secret: process.env.JWT_SECRET || 'React Starter Kit' }, // https://developers.facebook.com/ facebook: { id: process.env.FACEBOOK_APP_ID || '186244551745631', secret: process.env.FACEBOOK_APP_SECRET || 'a970ae3240ab4b9b8aae0f9f0661c6fc', }, // https://cloud.google.com/console/project google: { id: process.env.GOOGLE_CLIENT_ID || '251410730550-ahcg0ou5mgfhl8hlui1urru7jn5s12km.apps.googleusercontent.com', secret: process.env.GOOGLE_CLIENT_SECRET || 'Y8yR9yZAhm9jQ8FKAL8QIEcd', }, // https://apps.twitter.com/ twitter: { key: process.env.TWITTER_CONSUMER_KEY || 'Ie20AZvLJI2lQD5Dsgxgjauns', secret: process.env.TWITTER_CONSUMER_SECRET || 'KTZ6cxoKnEakQCeSpZlaUCJWGAlTEBJj0y2EMkUBujA7zWSvaQ', }, }, };
define([ 'jquery', 'underscore', 'backbone' ], function ($, _, Backbone) { var Application = Backbone.Model.extend({ idAttribute: 'token', defaults: { }, initialize: function () { var base = this; base.events = $.extend({}, Backbone.Events); }, launch: function () { var base = this; if (!base.get("restricted_to") || SmartBlocks.current_user.hasRight(base.get("restricted_to"))) { SmartBlocks.Methods.startMainLoading("Loading " + base.get('name'), 2, false); if (base.get("entry_point")) { base.ready = false; var block = SmartBlocks.Data.blocks.get(base.get("block_token")); var main = SmartBlocks.Blocks[block.get('name')].Main; console.log(base.get("block_token"), block, main); if (main[base.get("entry_point")]) { main[base.get("entry_point")](base); base.events.trigger("ready"); SmartBlocks.current_app = base; base.routeit(); console.log(base); } base.ready = true; // require([base.get("entry_point")], function (View) { // SmartBlocks.Methods.continueMainLoading(2); // var view = new View(); // SmartBlocks.Methods.render(view); // view.init(base); // base.ready = true; // base.events.trigger("ready"); // SmartBlocks.current_app = base; // base.routeit(); // }); } } else { SmartBlocks.basics.show_message("You don't have the rights to access this app"); SmartBlocks.router.back(); } }, quit: function () { var base = this; window.location = "#"; }, initRoutes: function (obj) { var base = this; var reload = !base.routes; base.routes = obj; if (reload) { base.routeit(); } }, route: function () { var base = this; if (!SmartBlocks.current_app || SmartBlocks.current_app.get("token") == base.get("token")) { base.routeit(); } base.current_url = SmartBlocks.Url.full; }, routeit: function () { var base = this; var app_routes = base.get("routing"); if (SmartBlocks.Url.params.length == 0) { if (base.routes) { if (base.routes[""]) base.routes[""].apply(base, parameters); } return; } for (var k in base.routes) { var route = base.routes[k]; var do_it = true; var parameters = []; var route_params = k.split("/"); for (var j in SmartBlocks.Url.params) { var param = SmartBlocks.Url.params[j]; if (route_params[j]) { if (route_params[j][0] == ":") { parameters.push(param); } else { if (param != route_params[j]) { do_it = false; } } } else { do_it = false; } } if (do_it) { if (base.routes) route.apply(base, parameters); break; } } }, getBlock: function () { var base = this; var block = SmartBlocks.Data.blocks.get(base.get("block_token")); return block; } }); return Application; });
import Q from "q"; export default class AppComponents { constructor(...listOfComponents) { this._list = listOfComponents; } onAppConfig(config) { return this._list.forEach(this._invokeHook("onAppConfig", config)); } onBeforeAppBootstrapped(bootstrapper) { return this._list.forEach(this._invokeHook("onBeforeAppBootstrapped", bootstrapper)); } register(specs) { return Q.all(this._list.map( (component) => this._registerComponent(component, specs) )); } onAppComponentsRegistered(bootstrapper) { return this._list.forEach(this._invokeHook("onAppComponentsRegistered", bootstrapper)); } onAppBootstrapped(container) { return this._list.forEach(this._invokeHook("onAppBootstrapped", container)); } _registerComponent(component, specs) { return Q(component.register(specs)).then((registration = {}) => ( specs.register({ name: component.metadata.name, registration }) )); } _invokeHook(hook, ...args) { return (component) => { if (typeof component[hook] === "function") { return component[hook](...args); } }; } }
var assert = require("assert"); var path = require("path"); var local = path.join.bind(path, __dirname); var promisify = require("promisify-node"); var Promise = require("nodegit-promise"); // Have to wrap exec, since it has a weird callback signature. var exec = promisify(function(command, opts, callback) { return require("child_process").exec(command, opts, callback); }); describe("Signature", function() { var NodeGit = require("../../"); var Repository = NodeGit.Repository; var Signature = NodeGit.Signature; var reposPath = local("../repos/workdir"); var name = "Bob Gnarley"; var email = "gnarlee@bob.net"; var arbitraryDate = 123456789; var timezoneOffset = 60; it("can be created at an arbitrary time", function() { var create = Signature.create; var signature = create(name, email, arbitraryDate, timezoneOffset); assert.equal(signature.name(), name); assert.equal(signature.email(), email); assert.equal(signature.when().time(), arbitraryDate); assert.equal(signature.when().offset(), 60); }); it("can be created now", function() { var signature = Signature.now(name, email); var now = new Date(); var when = signature.when(); var diff = Math.abs(when.time() - now/1000); assert.equal(signature.name(), name); assert.equal(signature.email(), email); assert(diff <= 1); // libgit2 does its timezone offsets backwards from javascript assert.equal(when.offset(), -now.getTimezoneOffset()); }); it("can get a default signature when no user name is set", function() { var savedUserName; var savedUserEmail; var cleanUp = function() { return exec("git config --global user.name \"" + savedUserName + "\"") .then(function() { return exec( "git config --global user.email \"" + savedUserEmail + "\""); }); }; return exec("git config --global user.name") .then(function(userName) { savedUserName = userName.trim(); return exec("git config --global user.email"); }) .then(function(userEmail) { savedUserEmail = userEmail.trim(); return exec("git config --global --unset user.name"); }) .then(function() { return exec("git config --global --unset user.email"); }) .then(function() { return Repository.open(reposPath); }) .then(function(repo) { var sig = repo.defaultSignature(); assert.equal(sig.name(), "unknown"); assert.equal(sig.email(), "unknown@unknown.com"); }) .then(function() { cleanUp(); }) .catch(function(e) { cleanUp() .then(function() { return Promise.reject(e); }); }); }); });
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { actions as counterActions } from '../../redux/modules/counter'; // We define mapStateToProps where we'd normally use // the @connect decorator so the data requirements are clear upfront, but then // export the decorated component after the main class definition so // the component can be tested w/ and w/o being connected. // See: http://rackt.github.io/redux/docs/recipes/WritingTests.html const mapStateToProps = (state) => ({ counter: state.counter, }); class HomeView extends React.Component { static propTypes = { counter: React.PropTypes.number.isRequired, doubleAsync: React.PropTypes.func.isRequired, increment: React.PropTypes.func.isRequired, }; handleClick = () => this.props.increment(1); render() { return ( <div className="container text-center"> <h1>Welcome to the React Redux Starter Kit</h1> <h2> Sample Counter:&nbsp; <span> {this.props.counter} </span> </h2> <button className="btn btn-default" onClick={this.handleClick} > Increment </button> <button className="btn btn-default" onClick={this.props.doubleAsync} > Double (Async) </button> <hr /> <Link to="/404">Go to 404 Page</Link> </div> ); } } export default connect(mapStateToProps, counterActions)(HomeView);
export class TileLeaf { constructor(parent, id) { this.parent = parent; this.id = id; } clone() { return new TileLeaf(this.parent, this.id); } searchLeaf(id) { return this.id === id ? this : null; } } export const SplitType = { Horizontal: Symbol('horizontal'), Vertical: Symbol('vertical') }; const Direction = { Left: Symbol('left'), Right: Symbol('right') }; export class ContainerKnot { constructor(parent, left, right, type) { this.parent = parent; this.left = left; this.right = right; this.left.parent = this; this.right.parent = this; this.split_type = type; } clone() { return new ContainerKnot( this.parent, this.left, this.right, this.split_type ); } replaceChild(old_child, new_child) { if (this.left === old_child) { this.left = new_child; new_child.parent = this; } else if (this.right === old_child) { this.right = new_child; new_child.parent = this; } else { console.log('Invalid old child', old_child); } } getChild(direction) { if (direction === Direction.Left) { return this.left; } else { return this.right; } } getSiblingOf(child) { if (this.left === child) { return this.right; } else if (this.right === child) { return this.left; } else { console.log('Not a child', child); return null; } } searchLeaf(id) { return this.left.searchLeaf(id) || this.right.searchLeaf(id); } } export default class TileTree { constructor(root, next_id) { this.root = root || new TileLeaf(null, 0); this.next_id = next_id || 1; } // Note: // Clone both self and its root because react component detects different properties. // <App/> component takes the root as property, not tree. clone() { return new TileTree(this.root.clone(), this.next_id); } split(id, split_type) { const target_leaf = this.root.searchLeaf(id); if (target_leaf === null) { console.log('Invalid id: ' + id); return null; } const new_leaf = new TileLeaf(null, this.next_id++); const target_parent = target_leaf.parent; const new_container = new ContainerKnot(target_parent, target_leaf, new_leaf, split_type); if (target_parent === null) { this.root = new_container; } else { target_parent.replaceChild(target_leaf, new_container); } return new_leaf.id; } remove(id) { const target_leaf = this.root.searchLeaf(id); if (target_leaf === null) { console.log('Invalid id: ' + id); return null; // Error } const target_parent = target_leaf.parent; if (target_parent === null) { return null; // Root } const sibling = target_parent.getSiblingOf(target_leaf); const closer_dir = target_parent.left === sibling ? Direction.Right : Direction.Left; if (sibling === null) { return null; // Error } const parent_of_parent = target_parent.parent; if (parent_of_parent === null) { this.root = sibling; sibling.parent = null; } else { parent_of_parent.replaceChild(target_parent, sibling); } let c = sibling; while (c.id === undefined) { c = c.getChild(closer_dir); } return c.id; } getNeighborImpl(target_node, direction, split_type) { const parent = target_node.parent; if (parent === null) { // Reached root; not found return null; } if (parent.split_type === split_type) { const opposite_dir = direction === Direction.Left ? Direction.Right : Direction.Left; const sibling = parent.getChild(opposite_dir); if (sibling === target_node) { // Found! let c = parent.getChild(direction); while (c instanceof ContainerKnot) { if (c.split_type === split_type) { c = c.getChild(opposite_dir); } else { c = c.left; } } return c.id; } } return this.getNeighborImpl(parent, direction, split_type); } getNeighbor(id, direction, split_type) { let target_leaf = this.root.searchLeaf(id); if (target_leaf === null) { console.log('Invalid id: ' + id); return null; // Error } return this.getNeighborImpl(target_leaf, direction, split_type); } getLeftOf(id) { return this.getNeighbor(id, Direction.Left, SplitType.Vertical); } getRightOf(id) { return this.getNeighbor(id, Direction.Right, SplitType.Vertical); } getUpOf(id) { return this.getNeighbor(id, Direction.Left, SplitType.Horizontal); } getDownOf(id) { return this.getNeighbor(id, Direction.Right, SplitType.Horizontal); } switchSplitType(id) { let target_leaf = this.root.searchLeaf(id); if (target_leaf === null || target_leaf.parent === null) { return; } target_leaf.parent.split_type = target_leaf.parent.split_type === SplitType.Vertical ? SplitType.Horizontal : SplitType.Vertical; // Return new tree for updating react component return this.clone(); } swapTiles(id) { const t = this.root.searchLeaf(id); if (t === null || t.parent === null) { return; } const p = t.parent; const tmp = p.right; p.right = p.left; p.left = tmp; // Return new tree for updating react component return this.clone(); } }
import { connect } from 'react-redux'; import TrialForm from '../../../components/TimelineNodeEditor/TrialForm'; import * as editorActions from '../../../actions/editorActions'; const onChangePluginType = (dispatch, newPluginVal) => { dispatch(editorActions.onPluginTypeChange(newPluginVal)); } const mapStateToProps = (state, ownProps) => { let experimentState = state.experimentState; let trial = experimentState[experimentState.previewId]; return { pluginType: trial.parameters.type, }; } const mapDispatchToProps = (dispatch,ownProps) => ({ onChange: (newPluginVal) => { onChangePluginType(dispatch, newPluginVal); }, }) export default connect(mapStateToProps, mapDispatchToProps)(TrialForm);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _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 _simpleAssign = require('simple-assign'); var _simpleAssign2 = _interopRequireDefault(_simpleAssign); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _transitions = require('../styles/transitions'); var _transitions2 = _interopRequireDefault(_transitions); var _colorManipulator = require('../utils/colorManipulator'); var _EnhancedButton = require('../internal/EnhancedButton'); var _EnhancedButton2 = _interopRequireDefault(_EnhancedButton); var _FontIcon = require('../FontIcon'); var _FontIcon2 = _interopRequireDefault(_FontIcon); var _Paper = require('../Paper'); var _Paper2 = _interopRequireDefault(_Paper); var _childUtils = require('../utils/childUtils'); var _warning = require('warning'); var _warning2 = _interopRequireDefault(_warning); var _propTypes = require('../utils/propTypes'); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function getStyles(props, context) { var floatingActionButton = context.muiTheme.floatingActionButton; var backgroundColor = props.backgroundColor || floatingActionButton.color; var iconColor = floatingActionButton.iconColor; if (props.disabled) { backgroundColor = props.disabledColor || floatingActionButton.disabledColor; iconColor = floatingActionButton.disabledTextColor; } else if (props.secondary) { backgroundColor = floatingActionButton.secondaryColor; iconColor = floatingActionButton.secondaryIconColor; } return { root: { transition: _transitions2.default.easeOut(), display: 'inline-block' }, container: { backgroundColor: backgroundColor, transition: _transitions2.default.easeOut(), position: 'relative', height: floatingActionButton.buttonSize, width: floatingActionButton.buttonSize, padding: 0, overflow: 'hidden', borderRadius: '50%', textAlign: 'center', verticalAlign: 'bottom' }, containerWhenMini: { height: floatingActionButton.miniSize, width: floatingActionButton.miniSize }, overlay: { transition: _transitions2.default.easeOut(), top: 0 }, overlayWhenHovered: { backgroundColor: (0, _colorManipulator.fade)(iconColor, 0.4) }, icon: { height: floatingActionButton.buttonSize, lineHeight: floatingActionButton.buttonSize + 'px', fill: iconColor, color: iconColor }, iconWhenMini: { height: floatingActionButton.miniSize, lineHeight: floatingActionButton.miniSize + 'px' } }; } var FloatingActionButton = function (_Component) { _inherits(FloatingActionButton, _Component); function FloatingActionButton() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, FloatingActionButton); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(FloatingActionButton)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { hovered: false, touch: false, zDepth: undefined }, _this.handleMouseDown = function (event) { // only listen to left clicks if (event.button === 0) { _this.setState({ zDepth: _this.props.zDepth + 1 }); } if (_this.props.onMouseDown) _this.props.onMouseDown(event); }, _this.handleMouseUp = function (event) { _this.setState({ zDepth: _this.props.zDepth }); if (_this.props.onMouseUp) _this.props.onMouseUp(event); }, _this.handleMouseLeave = function (event) { if (!_this.refs.container.isKeyboardFocused()) _this.setState({ zDepth: _this.props.zDepth, hovered: false }); if (_this.props.onMouseLeave) _this.props.onMouseLeave(event); }, _this.handleMouseEnter = function (event) { if (!_this.refs.container.isKeyboardFocused() && !_this.state.touch) { _this.setState({ hovered: true }); } if (_this.props.onMouseEnter) _this.props.onMouseEnter(event); }, _this.handleTouchStart = function (event) { _this.setState({ touch: true, zDepth: _this.props.zDepth + 1 }); if (_this.props.onTouchStart) _this.props.onTouchStart(event); }, _this.handleTouchEnd = function (event) { _this.setState({ zDepth: _this.props.zDepth }); if (_this.props.onTouchEnd) _this.props.onTouchEnd(event); }, _this.handleKeyboardFocus = function (event, keyboardFocused) { if (keyboardFocused && !_this.props.disabled) { _this.setState({ zDepth: _this.props.zDepth + 1 }); _this.refs.overlay.style.backgroundColor = (0, _colorManipulator.fade)(getStyles(_this.props, _this.context).icon.color, 0.4); } else if (!_this.state.hovered) { _this.setState({ zDepth: _this.props.zDepth }); _this.refs.overlay.style.backgroundColor = 'transparent'; } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(FloatingActionButton, [{ key: 'componentWillMount', value: function componentWillMount() { this.setState({ zDepth: this.props.disabled ? 0 : this.props.zDepth }); } }, { key: 'componentDidMount', value: function componentDidMount() { process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.iconClassName || !this.props.children, 'You have set both an iconClassName and a child icon. ' + 'It is recommended you use only one method when adding ' + 'icons to FloatingActionButtons.') : void 0; } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.disabled !== this.props.disabled) { this.setState({ zDepth: nextProps.disabled ? 0 : this.props.zDepth }); } } }, { key: 'render', value: function render() { var _props = this.props; var className = _props.className; var disabled = _props.disabled; var mini = _props.mini; var secondary = _props.secondary; var // eslint-disable-line no-unused-vars iconStyle = _props.iconStyle; var iconClassName = _props.iconClassName; var other = _objectWithoutProperties(_props, ['className', 'disabled', 'mini', 'secondary', 'iconStyle', 'iconClassName']); var prepareStyles = this.context.muiTheme.prepareStyles; var styles = getStyles(this.props, this.context); var iconElement = void 0; if (iconClassName) { iconElement = _react2.default.createElement(_FontIcon2.default, { className: iconClassName, style: (0, _simpleAssign2.default)({}, styles.icon, mini && styles.iconWhenMini, iconStyle) }); } var children = (0, _childUtils.extendChildren)(this.props.children, { style: (0, _simpleAssign2.default)({}, styles.icon, mini && styles.iconWhenMini, iconStyle) }); var buttonEventHandlers = disabled ? null : { onMouseDown: this.handleMouseDown, onMouseUp: this.handleMouseUp, onMouseLeave: this.handleMouseLeave, onMouseEnter: this.handleMouseEnter, onTouchStart: this.handleTouchStart, onTouchEnd: this.handleTouchEnd, onKeyboardFocus: this.handleKeyboardFocus }; return _react2.default.createElement( _Paper2.default, { className: className, style: (0, _simpleAssign2.default)(styles.root, this.props.style), zDepth: this.state.zDepth, circle: true }, _react2.default.createElement( _EnhancedButton2.default, _extends({}, other, buttonEventHandlers, { ref: 'container', disabled: disabled, style: (0, _simpleAssign2.default)(styles.container, this.props.mini && styles.containerWhenMini, iconStyle), focusRippleColor: styles.icon.color, touchRippleColor: styles.icon.color }), _react2.default.createElement( 'div', { ref: 'overlay', style: prepareStyles((0, _simpleAssign2.default)(styles.overlay, this.state.hovered && !this.props.disabled && styles.overlayWhenHovered)) }, iconElement, children ) ) ); } }]); return FloatingActionButton; }(_react.Component); FloatingActionButton.propTypes = { /** * This value will override the default background color for the button. * However it will not override the default disabled background color. * This has to be set separately using the disabledColor attribute. */ backgroundColor: _react.PropTypes.string, /** * This is what displayed inside the floating action button; for example, a SVG Icon. */ children: _react.PropTypes.node, /** * The css class name of the root element. */ className: _react.PropTypes.string, /** * Disables the button if set to true. */ disabled: _react.PropTypes.bool, /** * This value will override the default background color for the button when it is disabled. */ disabledColor: _react.PropTypes.string, /** * The URL to link to when the button is clicked. */ href: _react.PropTypes.string, /** * The icon within the FloatingActionButton is a FontIcon component. * This property is the classname of the icon to be displayed inside the button. * An alternative to adding an iconClassName would be to manually insert a * FontIcon component or custom SvgIcon component or as a child of FloatingActionButton. */ iconClassName: _react.PropTypes.string, /** * This is the equivalent to iconClassName except that it is used for * overriding the inline-styles of the FontIcon component. */ iconStyle: _react.PropTypes.object, /** * If true, the button will be a small floating action button. */ mini: _react.PropTypes.bool, /** @ignore */ onMouseDown: _react.PropTypes.func, /** @ignore */ onMouseEnter: _react.PropTypes.func, /** @ignore */ onMouseLeave: _react.PropTypes.func, /** @ignore */ onMouseUp: _react.PropTypes.func, /** @ignore */ onTouchEnd: _react.PropTypes.func, /** @ignore */ onTouchStart: _react.PropTypes.func, /** * If true, the button will use the secondary button colors. */ secondary: _react.PropTypes.bool, /** * Override the inline-styles of the root element. */ style: _react.PropTypes.object, /** * The zDepth of the underlying `Paper` component. */ zDepth: _propTypes2.default.zDepth }; FloatingActionButton.defaultProps = { disabled: false, mini: false, secondary: false, zDepth: 2 }; FloatingActionButton.contextTypes = { muiTheme: _react.PropTypes.object.isRequired }; exports.default = FloatingActionButton;
// toArray "use strict" // Imports. const { Writable } = require("stream") // toArray :: Stream a -> Promise [a] const toArray = stream => { const source = [] const write = stream.pipe( new Writable({ objectMode: true, write(chunk, encoding, callback) { source.push(chunk) callback() } }) ) return new Promise((resolve, reject) => { write.on("finish", () => { resolve(source) }) write.on("error", reject) }) } // Exports. module.exports = toArray
var ScaledField = require('../../js/fields/scaledfield'); var CircleField = require('../../js/fields/circlefield'); var Rect = require('../../js/geometry/rect'); describe('ScaledField Tests', function() { describe('valueAt()', function() { it('should return the scaled value everywhere', function() { var bounds = new Rect(0, 0, 100, 100); var circleField = new CircleField(48, 48, 30, bounds); var scaledField = new ScaledField(circleField, 2, bounds); expect(scaledField.valueAt(14, 91)).toBe(2*circleField.valueAt(14, 91)); expect(scaledField.valueAt(82, 47)).toBe(2*circleField.valueAt(82, 47)); expect(scaledField.valueAt(50, 11)).toBe(2*circleField.valueAt(50, 11)); }); }); });
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A menu item class that supports three state checkbox semantics. * * @author eae@google.com (Emil A Eklund) */ goog.provide('goog.ui.TriStateMenuItem'); goog.provide('goog.ui.TriStateMenuItem.State'); goog.require('goog.dom.classlist'); goog.require('goog.ui.Component'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.TriStateMenuItemRenderer'); goog.require('goog.ui.registry'); /** * Class representing a three state checkbox menu item. * * @param {goog.ui.ControlContent} content Text caption or DOM structure * to display as the content of the item (use to add icons or styling to * menus). * @param {Object=} opt_model Data/model associated with the menu item. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for * document interactions. * @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer. * @constructor * @extends {goog.ui.MenuItem} * * TODO(attila): Figure out how to better integrate this into the * goog.ui.Control state management framework. * @final */ goog.ui.TriStateMenuItem = function(content, opt_model, opt_domHelper, opt_renderer) { goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper, opt_renderer || new goog.ui.TriStateMenuItemRenderer()); this.setCheckable(true); }; goog.inherits(goog.ui.TriStateMenuItem, goog.ui.MenuItem); /** * Checked states for component. * @enum {number} */ goog.ui.TriStateMenuItem.State = { /** * Component is not checked. */ NOT_CHECKED: 0, /** * Component is partially checked. */ PARTIALLY_CHECKED: 1, /** * Component is fully checked. */ FULLY_CHECKED: 2 }; /** * Menu item's checked state. * @type {goog.ui.TriStateMenuItem.State} * @private */ goog.ui.TriStateMenuItem.prototype.checkState_ = goog.ui.TriStateMenuItem.State.NOT_CHECKED; /** * Whether the partial state can be toggled. * @type {boolean} * @private */ goog.ui.TriStateMenuItem.prototype.allowPartial_ = false; /** * @return {goog.ui.TriStateMenuItem.State} The menu item's check state. */ goog.ui.TriStateMenuItem.prototype.getCheckedState = function() { return this.checkState_; }; /** * Sets the checked state. * @param {goog.ui.TriStateMenuItem.State} state The checked state. */ goog.ui.TriStateMenuItem.prototype.setCheckedState = function(state) { this.setCheckedState_(state); this.allowPartial_ = state == goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED; }; /** * Sets the checked state and updates the CSS styling. Dispatches a * {@code CHECK} or {@code UNCHECK} event prior to changing the component's * state, which may be caught and canceled to prevent the component from * changing state. * @param {goog.ui.TriStateMenuItem.State} state The checked state. * @private */ goog.ui.TriStateMenuItem.prototype.setCheckedState_ = function(state) { if (this.dispatchEvent(state != goog.ui.TriStateMenuItem.State.NOT_CHECKED ? goog.ui.Component.EventType.CHECK : goog.ui.Component.EventType.UNCHECK)) { this.setState(goog.ui.Component.State.CHECKED, state != goog.ui.TriStateMenuItem.State.NOT_CHECKED); this.checkState_ = state; this.updatedCheckedStateClassNames_(); } }; /** @override */ goog.ui.TriStateMenuItem.prototype.performActionInternal = function(e) { switch (this.getCheckedState()) { case goog.ui.TriStateMenuItem.State.NOT_CHECKED: this.setCheckedState_(this.allowPartial_ ? goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED : goog.ui.TriStateMenuItem.State.FULLY_CHECKED); break; case goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED: this.setCheckedState_(goog.ui.TriStateMenuItem.State.FULLY_CHECKED); break; case goog.ui.TriStateMenuItem.State.FULLY_CHECKED: this.setCheckedState_(goog.ui.TriStateMenuItem.State.NOT_CHECKED); break; } var checkboxClass = goog.getCssName( this.getRenderer().getCssClass(), 'checkbox'); var clickOnCheckbox = e.target && goog.dom.classlist.contains( /** @type {!Element} */ (e.target), checkboxClass); return this.dispatchEvent(clickOnCheckbox || this.allowPartial_ ? goog.ui.Component.EventType.CHANGE : goog.ui.Component.EventType.ACTION); }; /** * Updates the extra class names applied to the menu item element. * @private */ goog.ui.TriStateMenuItem.prototype.updatedCheckedStateClassNames_ = function() { var renderer = this.getRenderer(); renderer.enableExtraClassName( this, goog.getCssName(renderer.getCssClass(), 'partially-checked'), this.getCheckedState() == goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED); renderer.enableExtraClassName( this, goog.getCssName(renderer.getCssClass(), 'fully-checked'), this.getCheckedState() == goog.ui.TriStateMenuItem.State.FULLY_CHECKED); }; // Register a decorator factory function for goog.ui.TriStateMenuItemRenderer. goog.ui.registry.setDecoratorByClassName( goog.ui.TriStateMenuItemRenderer.CSS_CLASS, function() { // TriStateMenuItem defaults to using TriStateMenuItemRenderer. return new goog.ui.TriStateMenuItem(null); });
const gulp = require('gulp') const mocha = require('gulp-mocha') const app = require('./tests/app.js') app.listen(1337) gulp.task('mocha', () => gulp.src('tests/app.spec.js') .pipe(mocha()) .once('end', () => process.exit()) ) gulp.task('default', ['mocha'])
import disallow from "../disallow"; describe("disallow", () => { it("should negate false values to true", () => { expect(disallow(() => false)()).toBe(true); }); it("should negate true values to false", () => { expect(disallow(() => true)()).toBe(false); }); it("should ignore object values", () => { const obj = { some: "object" }; expect(disallow(() => obj)()).toBe(obj); }); it("should ignore undefined values", () => { const obj = undefined; expect(disallow(() => obj)()).toBe(obj); }); it("should ignore string values", () => { const obj = "abc"; expect(disallow(() => obj)()).toBe(obj); }); it("should ignore number values", () => { const obj = 123; expect(disallow(() => obj)()).toBe(obj); }); it("should ignore array values", () => { const obj = []; expect(disallow(() => obj)()).toBe(obj); }); });
var passport = require('passport'), bcrypt = require('bcrypt'), async = require('async'), LocalStrategy = require('passport-local').Strategy, Sequelize = require('sequelize'), User = require('../db/sql').User appRoute = require('../routes/application'); //Passport required serialization passport.serializeUser(function(user, done) { done(null, user.uuid); }); // passport required deserialize find user given id from serialize passport.deserializeUser(function(uuid, done) { User.find({ where: { uuid: uuid } }) .success(function(user) { done(null, user); }) .failure(function(error) { done(error, null); }) }); // Use bcrypt to hash users plaintext password - plaintext is bad - hashed is good - bcrypt is great exports.hashPassword = function(plaintext_password, callback) { bcrypt.genSalt(10, function(err, salt) { if (err) { return new Error('app/passport/passport.js: bcrypt salting error'); } bcrypt.hash(plaintext_password, salt, function(error, password) { if (error) { return new Error('app/passport/passport.js: bcrypt hashing error'); } callback(null, password); }); }); } // Helper function to test for valid value function isEmptyOrNull(value) { return (value === null || value == '' || value == undefined); }; // Create a local user exports.localAuthentication = function(req, res) { var password = null; async.waterfall([ // make sure username and email have not already been taken function validateUsernameAndEmail(nextStep) { User.find({ where: Sequelize.or({ username: req.body.username }, { email_address: req.body.email_address }) }) .done(function(error, user) { if (user) { nextStep({ message: 'Username is already being used' }); } nextStep(null); }); }, // encrypt password and pass it to create user function encryptPassword(nextStep) { if (req.body.password === req.body.confirm_password) { exports.hashPassword(req.body.password, nextStep) } else { nextStep({ message: 'Passwords do not match' }); } }, // create user with hashed password function createUser(hashedPassword, complete) { User.create({ username: req.body.username, first_name: req.body.first_name, email_address: req.body.email_address, last_name: req.body.last_name, password: hashedPassword }) .success(function(user) { req.user = req.session.user = user; complete(null, { message: 'User successfully created, you can now login' }); }) .error(function(err) { complete({ message: err }); }); complete(null, 'done'); } ], function finalize(error, result) { if (error) { req.flash('error', error.message); res.redirect('/create'); } else { req.flash('success', result.message); appRoute.login(req, res); } }); }; //Sign in using username or email and password. passport.use(new LocalStrategy(function(usernameOrEmail, password, done) { async.waterfall([ // look for user with given username or email function findUser(nextStep) { function error() { return done(null, false, { message: 'User not found.' }); } User.find({ where: Sequelize.or({ username: usernameOrEmail }, { email_address: usernameOrEmail }) }).then(function(user) { if (user !== null) { nextStep(null, user); } else { return nextStep({ message: 'User not found' }); } }, function(error) { return nextStep({ message: 'User not found' }); }) }, // make sure password is valid function comparePassword(user, complete) { if (!user) { complete({ message: 'Invalid email or password.' }); } else { bcrypt.compare(password, user.password, function(err, match) { if (match) { complete(null, user); } else { complete({ message: 'Invalid email or password.' }); } }); } } ], function finalize(error, user) { if (error) { done(null, false, { message: error.message }); } else { done(null, user); } }); }));
var sharedHandlers = require("./sharedHandlers"); var textareaHandlers = exports; textareaHandlers["virt.dom.TextArea.getValue"] = sharedHandlers.getValue; textareaHandlers["virt.dom.TextArea.setValue"] = sharedHandlers.setValue; textareaHandlers["virt.dom.TextArea.getSelection"] = sharedHandlers.getSelection; textareaHandlers["virt.dom.TextArea.setSelection"] = sharedHandlers.setSelection; textareaHandlers["virt.dom.TextArea.focus"] = sharedHandlers.focus; textareaHandlers["virt.dom.TextArea.blur"] = sharedHandlers.blur;
import React from 'react'; import TestUtils from 'react-dom/test-utils'; import { expect } from 'chai'; import { init, childrenMatcher, containerPropsMatcher, getInnerHTML, getElementWithClass, setInputValue } from '../helpers'; import AutosuggestApp, { renderSuggestionsContainer } from './AutosuggestApp'; describe('Autosuggest with renderSuggestionsContainer', () => { beforeEach(() => { init(TestUtils.renderIntoDocument(<AutosuggestApp />)); renderSuggestionsContainer.resetHistory(); setInputValue('c '); }); it('should render whatever renderSuggestionsContainer returns', () => { expect(getElementWithClass('my-suggestions-container-footer')).not.to.equal( null ); expect(getInnerHTML(getElementWithClass('my-query'))).to.equal('c'); }); it('should call renderSuggestionsContainer once with the right parameters', () => { expect(renderSuggestionsContainer).to.have.been.calledOnce; expect(renderSuggestionsContainer).to.be.calledWith({ containerProps: containerPropsMatcher, children: childrenMatcher, query: 'c' }); }); });
(function() { 'use strict'; var Ractive = window.Ractive, require = window.require = Ractive.require, _ractiveControllers = {}, _fireController = Ractive.fireController; Ractive.controllerInjection = function(name, controller) { _ractiveControllers[name] = _ractiveControllers[name] || []; if (typeof controller == 'function' || Object.prototype.toString.call(controller) == '[object Array]') { _ractiveControllers[name].push(controller); } }; function _callControllers(controllers, component, data, el, config, i, done) { i = i || 0; var $i18nService = DependencyInjection.injector.view.get('$i18nService'); if (i < controllers.length) { DependencyInjection.injector.view.invoke(null, controllers[i], { view: { $component: function() { return function(config) { config.data = $.extend(true, { _: $i18nService._ }, config.data || {}); return component(config); }; }, $data: function() { return data; }, $el: function() { return $(el); }, $config: function() { return config; }, $next: function() { return function() { _callControllers(controllers, component, data, el, config, ++i, done); }; } } }); } else if (done) { done(); } } Ractive.fireController = function(name, Component, data, el, config, callback) { if (_ractiveControllers[name]) { return _callControllers(_ractiveControllers[name], Component, data, el, config, 0, function() { _fireController(name, Component, data, el, config, callback); }); } _fireController(name, Component, data, el, config, callback); }; window.bootstrap = function(func, requiresBefore) { DependencyInjection.service('$socket', function() { return io(); }); require('/public/common/common-i18n-model.js') .then(function() { return require('/public/common/common-abstract-model.js'); }) .then(function() { return require('/public/common/common-abstract-service.js'); }) .then(function() { return require('/public/favicon/favicon-service.js'); }) .then(function() { return require('/public/shortcuts/shortcuts-service.js'); }) .then(function() { requiresBefore = requiresBefore || []; window.async.each(requiresBefore, function(requireBefore, next) { require(requireBefore).then(next); }, function() { Ractive.bootstrap(function($Page) { DependencyInjection.view('$Page', function() { return $Page; }); DependencyInjection.view('$Layout', [function() { return $Page.childrenRequire[0]; }]); require('/public/common/common-routes.js').then(function() { DependencyInjection.injector.view.invoke(null, func, { view: { $done: function() { return function done() { window.page(); }; } } }); }); }); }); }); }; })(this);
var Twitter = require('../lib/twitter').Twitter , config = require('./config') , assert = require('assert'); var twitter = new Twitter({ key: config.twitter_key , secret: config.twitter_secret }); describe('Twitter', function () { describe('#followerCount', function () { it('should get the # of followers a user has', function (done) { twitter.followerCount('chris6F', function (err, followers) { assert.ifError(err); assert(typeof followers === 'number'); assert(followers > 0); done(); }); }); it('should fail on an invalid username', function (done) { twitter.followerCount('', function (err) { assert(err); done(); }); }); }); describe('#urlTweets', function () { it('should get the # of tweets a url has', function (done) { twitter.urlTweets('http://twitter.com', function (err, tweets) { assert.ifError(err); assert(typeof tweets === 'number'); assert(tweets > 0); done(); }); }); it('should fail on an invalid url', function (done) { twitter.urlTweets('', function (err) { assert(err); done(); }); }); }); describe('#latestTweets', function () { it('should get the latest tweets from a user', function (done) { twitter.latestTweets('chris6f', function (err, tweets) { assert.ifError(err); assert(Array.isArray(tweets) && tweets.length); tweets.forEach(function (tweet) { assert(tweet.id); assert(tweet.text); assert(tweet.user); assert(tweet.date.getTime() > 0); assert(tweet.entities); }); done(); }); }); }); describe('#latestHashtagTweets', function () { it('should get the latest tweets by hashtag', function (done) { twitter.latestHashtagTweets('yolo', function (err, tweets) { assert.ifError(err); assert(Array.isArray(tweets) && tweets.length); tweets.forEach(function (tweet) { assert(tweet.id); assert(tweet.text); assert(tweet.user); assert(tweet.date.getTime() > 0); assert(tweet.entities); }); done(); }); }); }); });
!function(){var a={1:"'inci",5:"'inci",8:"'inci",70:"'inci",80:"'inci",2:"'nci",7:"'nci",20:"'nci",50:"'nci",3:"'รผncรผ",4:"'รผncรผ",100:"'รผncรผ",6:"'ncฤฑ",9:"'uncu",10:"'uncu",30:"'uncu",60:"'ฤฑncฤฑ",90:"'ฤฑncฤฑ"},b={delimiters:{thousands:".",decimal:","},abbreviations:{thousand:"bin",million:"milyon",billion:"milyar",trillion:"trilyon"},ordinal:function(b){if(0===b)return"'ฤฑncฤฑ";var c=b%10,d=b%100-c,e=b>=100?100:null;return a[c]||a[d]||a[e]},currency:{symbol:"โ‚บ"}};"undefined"!=typeof module&&module.exports&&(module.exports=b),"undefined"!=typeof window&&this.numeral&&this.numeral.language&&this.numeral.language("tr",b)}();
if (typeof jQuery !== 'undefined') { jQuery.fn.kalendae = function (options) { this.each(function (i, e) { if (e.tagName === 'INPUT') { //if element is an input, bind a popup calendar to the input. $(e).data('kalendae', new Kalendae.Input(element, options)); } else { //otherwise, insert a flat calendar into the element. $(e).data('kalendae', new Kalendae($.extend({}, {attachTo:element}, options))); } }); return this; } }
import Ember from 'ember'; export default Ember.Controller.extend({ model: [] });
๏ปฟclass EditorConfig { /** * Initialize wysiwyg * @param {string} folder */ initArea(folder, areaSelector) { areaSelector = areaSelector || '#Content'; const $contentArea = $(areaSelector); // this._initCkEditor($contentArea); this._initFroala($contentArea, folder); } _initCkEditor($contentArea) { const editor = CKEDITOR.instances.Content; editor.on( 'change', (evt) => { $contentArea.val(evt.editor.getData()); } ); } _initFroala($contentArea, folder) { const uploadFileUrl = location.origin + `/api/froala/upload-file/${folder}`; const allowedImageFormats = ['jpeg', 'jpg', 'png', 'gif']; $contentArea.froalaEditor({ // https://www.froala.com/wysiwyg-editor/docs/concepts/image/manager imageManagerLoadURL: location.origin + '/api/froala/get-images', imageManagerPageSize: 30, imageManagerLoadMethod: 'GET', imageManagerDeleteURL: '/api/froala/delete-image', imageManagerDeleteMethod: 'POST', // https://www.froala.com/wysiwyg-editor/docs/concepts/image/upload imageUploadParam: 'file', imageUploadURL: uploadFileUrl, imageUploadMethod: 'POST', imageMaxSize: 50 * 1024 * 1024, // Set max image size to 50MB. imageAllowedTypes: [...allowedImageFormats], // https://www.froala.com/wysiwyg-editor/docs/concepts/file/upload fileUploadParam: 'file', fileUploadURL: uploadFileUrl, fileMaxSize: 500 * 1024 * 1024, // Set max image size to 500MB. fileAllowedTypes: ['*'], fileUploadMethod: 'POST', //https://www.froala.com/wysiwyg-editor/docs/concepts/video/upload videoUploadParam: 'file', videoUploadURL: uploadFileUrl, videoUploadMethod: 'POST', videoMaxSize: 500 * 1024 * 1024, // Set max image size to 500MB. videoAllowedTypes: ['webm', 'mp4', 'ogg'], language: 'ru', heightMax: 500, fontSize: ['8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '30', '36', '48', '60', '72', '96', '100', '120'], key: 'OEM_LICENSE_KEY', toolbarButtons: [ 'fullscreen', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', '|', 'fontFamily', 'fontSize', 'color', 'inlineStyle', 'paragraphStyle', '|', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', '-', 'insertLink', 'insertImage', 'insertVideo', 'embedly', 'insertFile', 'insertTable', '|', 'emoticons', 'specialCharacters', 'insertHR', 'selectAll', 'clearFormatting', '|', 'print', 'spellChecker', 'help', 'html', ] }); } }