language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function parseRIFF(string){ var offset = 0; var chunks = {}; while (offset < string.length) { var id = string.substr(offset, 4); var len = parseInt(string.substr(offset + 4, 4).split('').map(function(i){ var unpadded = i.charCodeAt(0).toString(2); return (new Array(8 - unpadded.length + 1)).join('0') + unpadded }).join(''),2); var data = string.substr(offset + 4 + 4, len); offset += 4 + 4 + len; chunks[id] = chunks[id] || []; if (id == 'RIFF' || id == 'LIST') { chunks[id].push(parseRIFF(data)); } else { chunks[id].push(data); } } return chunks; }
function parseRIFF(string){ var offset = 0; var chunks = {}; while (offset < string.length) { var id = string.substr(offset, 4); var len = parseInt(string.substr(offset + 4, 4).split('').map(function(i){ var unpadded = i.charCodeAt(0).toString(2); return (new Array(8 - unpadded.length + 1)).join('0') + unpadded }).join(''),2); var data = string.substr(offset + 4 + 4, len); offset += 4 + 4 + len; chunks[id] = chunks[id] || []; if (id == 'RIFF' || id == 'LIST') { chunks[id].push(parseRIFF(data)); } else { chunks[id].push(data); } } return chunks; }
JavaScript
function doubleToString(num){ return [].slice.call( new Uint8Array( ( new Float64Array([num]) //create a float64 array ).buffer) //extract the array buffer , 0) // convert the Uint8Array into a regular array .map(function(e){ //since it's a regular array, we can now use map return String.fromCharCode(e) // encode all the bytes individually }) .reverse() //correct the byte endianness (assume it's little endian for now) .join('') // join the bytes in holy matrimony as a string }
function doubleToString(num){ return [].slice.call( new Uint8Array( ( new Float64Array([num]) //create a float64 array ).buffer) //extract the array buffer , 0) // convert the Uint8Array into a regular array .map(function(e){ //since it's a regular array, we can now use map return String.fromCharCode(e) // encode all the bytes individually }) .reverse() //correct the byte endianness (assume it's little endian for now) .join('') // join the bytes in holy matrimony as a string }
JavaScript
function prepareInit(callback) { if (!self.openSignalingChannel) { if (typeof self.transmitRoomOnce == 'undefined') self.transmitRoomOnce = true; // for custom socket.io over node.js implementation - visit - https://github.com/muaz-khan/WebRTC-Experiment/blob/master/socketio-over-nodejs self.openSignalingChannel = function(config) { var channel = config.channel || self.channel; var firebase = new Firebase('https://' + (self.firebase || 'chat') + '.firebaseIO.com/' + channel); firebase.channel = channel; firebase.on('child_added', function(data) { config.onmessage(data.val()); }); firebase.send = function(data) { this.push(data); }; if (!self.socket) self.socket = firebase; if (channel != self.channel || (self.isInitiator && channel == self.channel)) firebase.onDisconnect().remove(); if (config.onopen) setTimeout(config.onopen, 1); return firebase; }; if (!window.Firebase) { loadScript('https://cdn.firebase.com/v0/firebase.js', callback); } else callback(); } else callback(); }
function prepareInit(callback) { if (!self.openSignalingChannel) { if (typeof self.transmitRoomOnce == 'undefined') self.transmitRoomOnce = true; // for custom socket.io over node.js implementation - visit - https://github.com/muaz-khan/WebRTC-Experiment/blob/master/socketio-over-nodejs self.openSignalingChannel = function(config) { var channel = config.channel || self.channel; var firebase = new Firebase('https://' + (self.firebase || 'chat') + '.firebaseIO.com/' + channel); firebase.channel = channel; firebase.on('child_added', function(data) { config.onmessage(data.val()); }); firebase.send = function(data) { this.push(data); }; if (!self.socket) self.socket = firebase; if (channel != self.channel || (self.isInitiator && channel == self.channel)) firebase.onDisconnect().remove(); if (config.onopen) setTimeout(config.onopen, 1); return firebase; }; if (!window.Firebase) { loadScript('https://cdn.firebase.com/v0/firebase.js', callback); } else callback(); } else callback(); }
JavaScript
function captureUserMedia(callback, _session) { var session = _session || self.session; if (self.dontAttachStream) return callback(); if (isData(session) || (!self.isInitiator && session.oneway)) { self.attachStreams = []; return callback(); } var constraints = { audio: !!session.audio, video: !!session.video }; var screen_constraints = { audio: false, video: { mandatory: { chromeMediaSource: 'screen' }, optional: [] } }; if (session.screen) { _captureUserMedia(screen_constraints, constraints.audio || constraints.video ? function() { _captureUserMedia(constraints, callback); } : callback); } else _captureUserMedia(constraints, callback, session.audio && !session.video); function _captureUserMedia(forcedConstraints, forcedCallback, isRemoveVideoTracks) { var mediaConfig = { onsuccess: function(stream, returnBack) { if (returnBack) return forcedCallback && forcedCallback(stream); if (isRemoveVideoTracks && !moz) { stream = new window.webkitMediaStream(stream.getAudioTracks()); } var mediaElement = getMediaElement(stream, session); mediaElement.muted = true; stream.onended = function() { if (self.onstreamended) self.onstreamended(streamedObject); else if (mediaElement.parentNode) mediaElement.parentNode.removeChild(mediaElement); }; var streamid = getRandomString(); stream.streamid = streamid; var streamedObject = { stream: stream, streamid: streamid, mediaElement: mediaElement, blobURL: mediaElement.mozSrcObject || mediaElement.src, type: 'local', userid: self.userid || 'self', extra: self.extra }; var sObject = { stream: stream, userid: self.userid || 'self', streamid: streamid, type: 'local', streamObject: streamedObject, mediaElement: mediaElement }; self.attachStreams.push(stream); self.__attachStreams.push(sObject); self.streams[streamid] = self._getStream(sObject); self.onstream(streamedObject); if (forcedCallback) forcedCallback(stream); }, onerror: function() { var error; if (session.audio && !session.video) error = 'Microphone access is denied.'; else if (session.screen) { if (location.protocol === 'http:') error = '<https> is mandatory to capture screen.'; else error = 'Multi-capturing of screen is not allowed. Capturing process is denied. Are you enabled flag: "Enable screen capture support in getUserMedia"?'; } else error = 'Webcam access is denied.'; if (!self.onMediaError) throw error; self.onMediaError(error); }, mediaConstraints: self.mediaConstraints || { } }; mediaConfig.constraints = forcedConstraints || constraints; mediaConfig.media = self.media; getUserMedia(mediaConfig); } }
function captureUserMedia(callback, _session) { var session = _session || self.session; if (self.dontAttachStream) return callback(); if (isData(session) || (!self.isInitiator && session.oneway)) { self.attachStreams = []; return callback(); } var constraints = { audio: !!session.audio, video: !!session.video }; var screen_constraints = { audio: false, video: { mandatory: { chromeMediaSource: 'screen' }, optional: [] } }; if (session.screen) { _captureUserMedia(screen_constraints, constraints.audio || constraints.video ? function() { _captureUserMedia(constraints, callback); } : callback); } else _captureUserMedia(constraints, callback, session.audio && !session.video); function _captureUserMedia(forcedConstraints, forcedCallback, isRemoveVideoTracks) { var mediaConfig = { onsuccess: function(stream, returnBack) { if (returnBack) return forcedCallback && forcedCallback(stream); if (isRemoveVideoTracks && !moz) { stream = new window.webkitMediaStream(stream.getAudioTracks()); } var mediaElement = getMediaElement(stream, session); mediaElement.muted = true; stream.onended = function() { if (self.onstreamended) self.onstreamended(streamedObject); else if (mediaElement.parentNode) mediaElement.parentNode.removeChild(mediaElement); }; var streamid = getRandomString(); stream.streamid = streamid; var streamedObject = { stream: stream, streamid: streamid, mediaElement: mediaElement, blobURL: mediaElement.mozSrcObject || mediaElement.src, type: 'local', userid: self.userid || 'self', extra: self.extra }; var sObject = { stream: stream, userid: self.userid || 'self', streamid: streamid, type: 'local', streamObject: streamedObject, mediaElement: mediaElement }; self.attachStreams.push(stream); self.__attachStreams.push(sObject); self.streams[streamid] = self._getStream(sObject); self.onstream(streamedObject); if (forcedCallback) forcedCallback(stream); }, onerror: function() { var error; if (session.audio && !session.video) error = 'Microphone access is denied.'; else if (session.screen) { if (location.protocol === 'http:') error = '<https> is mandatory to capture screen.'; else error = 'Multi-capturing of screen is not allowed. Capturing process is denied. Are you enabled flag: "Enable screen capture support in getUserMedia"?'; } else error = 'Webcam access is denied.'; if (!self.onMediaError) throw error; self.onMediaError(error); }, mediaConstraints: self.mediaConstraints || { } }; mediaConfig.constraints = forcedConstraints || constraints; mediaConfig.media = self.media; getUserMedia(mediaConfig); } }
JavaScript
async function deployContract() { if (typeof window.ethereum !== 'undefined') { await requestAccount() const provider = new ethers.providers.Web3Provider(window.ethereum) const signer = provider.getSigner() const contract = new ethers.Contract(bountyFactoryAddress, BountyFactory.abi, signer) contract.on("BountyCreated", (address) => { console.log("Bounty created", address) setBountyAddress(address) }) try { const expiry = new Date().getTime() + 1000 const overrides = { value: ethers.utils.parseEther("0.1") // ether in this case MUST be a string }; const qq = await contract.createBounty(expiry, overrides); console.log('data: ', qq) } catch (err) { console.log("Error: ", err) } } }
async function deployContract() { if (typeof window.ethereum !== 'undefined') { await requestAccount() const provider = new ethers.providers.Web3Provider(window.ethereum) const signer = provider.getSigner() const contract = new ethers.Contract(bountyFactoryAddress, BountyFactory.abi, signer) contract.on("BountyCreated", (address) => { console.log("Bounty created", address) setBountyAddress(address) }) try { const expiry = new Date().getTime() + 1000 const overrides = { value: ethers.utils.parseEther("0.1") // ether in this case MUST be a string }; const qq = await contract.createBounty(expiry, overrides); console.log('data: ', qq) } catch (err) { console.log("Error: ", err) } } }
JavaScript
function renderProducts(doc) { let mainrow = document.createElement("div"); let imgcol = document.createElement("div"); let imgcontainer = document.createElement("div"); let img = document.createElement("img"); let desccol = document.createElement("div"); let name = document.createElement("h3"); let nameanchor = document.createElement("a"); let nametag = document.createElement("strong"); let location = document.createElement("h5"); let description = document.createElement("p"); let pricestockrow = document.createElement("div"); let pricestockcol1 = document.createElement("div"); let price = document.createElement("p"); let pricestockcol2 = document.createElement("div"); let stock = document.createElement("p"); // let addbutton = document.createElement("button"); // let buttonicon = document.createElement("i"); let linebreak = document.createElement("hr"); mainrow.classList.add("row", "wow", "fadeIn"); imgcol.classList.add("col-lg-5", "col-xl-4", "mb-4"); imgcontainer.classList.add("view", "overlay", "rounded", "z-depth-1"); img.classList.add("img-fluid", "img-thumbnail"); desccol.classList.add("col-lg-7", "col-xl-7", "ml-xl-4", "mb-3"); name.classList.add("font-weight-bold", "dark-grey-text"); nametag.classList.add("blue-grey-text", "font-weight-bold"); location.classList.add("mb-2"); description.classList.add("grey-text", "font-italic"); pricestockrow.classList.add("row"); pricestockcol1.classList.add("col"); price.classList.add("font-weight-bold"); pricestockcol2.classList.add("col"); stock.classList.add("text-right", "pr-2"); // addbutton.classList.add("btn-block", "btn-unique", "btn-lg"); // buttonicon.classList.add("fas", "fa-cart-plus", "ml-2"); mainrow.setAttribute("data-id", doc.id); // img.setAttribute("src", "./img/dummy.jpg"); img.setAttribute("src", doc.data().Image); if (!doc.data().Image) { img.setAttribute("src", "./img/dummy.jpg"); }; img.style.width = "23em"; img.style.height = "23em"; nameanchor.setAttribute("href", "/product.html"); // addbutton.setAttribute("type", "button"); nametag.textContent = doc.data().Location; // nametag.textContent = doc.data().Product; // location.textContent = doc.data().Location; location.textContent = doc.data().Product; description.textContent = doc.data().Description; price.textContent = doc.data().Price; if (doc.data().Quantity > 0) { stock.textContent = "Currently in stock"; } else { stock.textContent = "Out of stock"; }; mainrow.appendChild(imgcol); imgcol.appendChild(imgcontainer); imgcontainer.appendChild(img); mainrow.appendChild(desccol); desccol.appendChild(name); name.appendChild(nameanchor); nameanchor.appendChild(nametag); desccol.appendChild(location); desccol.appendChild(description); desccol.appendChild(pricestockrow); pricestockrow.appendChild(pricestockcol1); pricestockcol1.appendChild(price); pricestockrow.appendChild(pricestockcol2); pricestockcol2.appendChild(stock); // desccol.appendChild(addbutton); // addbutton.appendChild(buttonicon); productlist.appendChild(mainrow); productlist.appendChild(linebreak); }
function renderProducts(doc) { let mainrow = document.createElement("div"); let imgcol = document.createElement("div"); let imgcontainer = document.createElement("div"); let img = document.createElement("img"); let desccol = document.createElement("div"); let name = document.createElement("h3"); let nameanchor = document.createElement("a"); let nametag = document.createElement("strong"); let location = document.createElement("h5"); let description = document.createElement("p"); let pricestockrow = document.createElement("div"); let pricestockcol1 = document.createElement("div"); let price = document.createElement("p"); let pricestockcol2 = document.createElement("div"); let stock = document.createElement("p"); // let addbutton = document.createElement("button"); // let buttonicon = document.createElement("i"); let linebreak = document.createElement("hr"); mainrow.classList.add("row", "wow", "fadeIn"); imgcol.classList.add("col-lg-5", "col-xl-4", "mb-4"); imgcontainer.classList.add("view", "overlay", "rounded", "z-depth-1"); img.classList.add("img-fluid", "img-thumbnail"); desccol.classList.add("col-lg-7", "col-xl-7", "ml-xl-4", "mb-3"); name.classList.add("font-weight-bold", "dark-grey-text"); nametag.classList.add("blue-grey-text", "font-weight-bold"); location.classList.add("mb-2"); description.classList.add("grey-text", "font-italic"); pricestockrow.classList.add("row"); pricestockcol1.classList.add("col"); price.classList.add("font-weight-bold"); pricestockcol2.classList.add("col"); stock.classList.add("text-right", "pr-2"); // addbutton.classList.add("btn-block", "btn-unique", "btn-lg"); // buttonicon.classList.add("fas", "fa-cart-plus", "ml-2"); mainrow.setAttribute("data-id", doc.id); // img.setAttribute("src", "./img/dummy.jpg"); img.setAttribute("src", doc.data().Image); if (!doc.data().Image) { img.setAttribute("src", "./img/dummy.jpg"); }; img.style.width = "23em"; img.style.height = "23em"; nameanchor.setAttribute("href", "/product.html"); // addbutton.setAttribute("type", "button"); nametag.textContent = doc.data().Location; // nametag.textContent = doc.data().Product; // location.textContent = doc.data().Location; location.textContent = doc.data().Product; description.textContent = doc.data().Description; price.textContent = doc.data().Price; if (doc.data().Quantity > 0) { stock.textContent = "Currently in stock"; } else { stock.textContent = "Out of stock"; }; mainrow.appendChild(imgcol); imgcol.appendChild(imgcontainer); imgcontainer.appendChild(img); mainrow.appendChild(desccol); desccol.appendChild(name); name.appendChild(nameanchor); nameanchor.appendChild(nametag); desccol.appendChild(location); desccol.appendChild(description); desccol.appendChild(pricestockrow); pricestockrow.appendChild(pricestockcol1); pricestockcol1.appendChild(price); pricestockrow.appendChild(pricestockcol2); pricestockcol2.appendChild(stock); // desccol.appendChild(addbutton); // addbutton.appendChild(buttonicon); productlist.appendChild(mainrow); productlist.appendChild(linebreak); }
JavaScript
function renderProducts(doc, docID) { let mainrow = document.createElement("div"); let imgcol = document.createElement("div"); let imgcontainer = document.createElement("div"); let img = document.createElement("img"); let desccol = document.createElement("div"); let name = document.createElement("h3"); let nameanchor = document.createElement("a"); let nametag = document.createElement("strong"); let location = document.createElement("h5"); let description = document.createElement("p"); let pricestockrow = document.createElement("div"); let pricestockcol1 = document.createElement("div"); let price = document.createElement("p"); let pricestockcol2 = document.createElement("div"); let stock = document.createElement("p"); let deletebutton = document.createElement("button"); let buttonicon = document.createElement("i"); let linebreak = document.createElement("hr"); mainrow.classList.add("row", "wow", "fadeIn"); imgcol.classList.add("col-lg-5", "col-xl-4", "mb-4"); imgcontainer.classList.add("view", "overlay", "rounded", "z-depth-1"); img.classList.add("img-fluid", "img-thumbnail"); desccol.classList.add("col-lg-7", "col-xl-7", "ml-xl-4", "mb-3"); name.classList.add("font-weight-bold", "dark-grey-text"); nametag.classList.add("blue-grey-text", "font-weight-bold"); location.classList.add("mb-2"); description.classList.add("grey-text", "font-italic"); pricestockrow.classList.add("row"); pricestockcol1.classList.add("col"); price.classList.add("font-weight-bold"); pricestockcol2.classList.add("col"); stock.classList.add("text-right", "pr-2"); deletebutton.classList.add("btn-block", "btn-unique", "btn-lg"); mainrow.setAttribute("data-id", doc.id); img.setAttribute("src", doc.data().Image); img.setAttribute("alt", "productimg"); nameanchor.setAttribute("href", "/product.html"); deletebutton.setAttribute("type", "button"); deletebutton.setAttribute("id", docID); nametag.textContent = doc.data().Product; location.textContent = doc.data().Location; description.textContent = doc.data().Description; price.textContent = doc.data().Price; stock.textContent = "Currently in stock"; deletebutton.textContent = "Delete"; mainrow.appendChild(imgcol); imgcol.appendChild(imgcontainer); imgcontainer.appendChild(img); mainrow.appendChild(desccol); desccol.appendChild(name); name.appendChild(nameanchor); nameanchor.appendChild(nametag); desccol.appendChild(location); desccol.appendChild(description); desccol.appendChild(pricestockrow); pricestockrow.appendChild(pricestockcol1); pricestockcol1.appendChild(price); pricestockrow.appendChild(pricestockcol2); pricestockcol2.appendChild(stock); desccol.appendChild(deletebutton); deletebutton.appendChild(buttonicon); productlist.appendChild(mainrow); productlist.appendChild(linebreak); }
function renderProducts(doc, docID) { let mainrow = document.createElement("div"); let imgcol = document.createElement("div"); let imgcontainer = document.createElement("div"); let img = document.createElement("img"); let desccol = document.createElement("div"); let name = document.createElement("h3"); let nameanchor = document.createElement("a"); let nametag = document.createElement("strong"); let location = document.createElement("h5"); let description = document.createElement("p"); let pricestockrow = document.createElement("div"); let pricestockcol1 = document.createElement("div"); let price = document.createElement("p"); let pricestockcol2 = document.createElement("div"); let stock = document.createElement("p"); let deletebutton = document.createElement("button"); let buttonicon = document.createElement("i"); let linebreak = document.createElement("hr"); mainrow.classList.add("row", "wow", "fadeIn"); imgcol.classList.add("col-lg-5", "col-xl-4", "mb-4"); imgcontainer.classList.add("view", "overlay", "rounded", "z-depth-1"); img.classList.add("img-fluid", "img-thumbnail"); desccol.classList.add("col-lg-7", "col-xl-7", "ml-xl-4", "mb-3"); name.classList.add("font-weight-bold", "dark-grey-text"); nametag.classList.add("blue-grey-text", "font-weight-bold"); location.classList.add("mb-2"); description.classList.add("grey-text", "font-italic"); pricestockrow.classList.add("row"); pricestockcol1.classList.add("col"); price.classList.add("font-weight-bold"); pricestockcol2.classList.add("col"); stock.classList.add("text-right", "pr-2"); deletebutton.classList.add("btn-block", "btn-unique", "btn-lg"); mainrow.setAttribute("data-id", doc.id); img.setAttribute("src", doc.data().Image); img.setAttribute("alt", "productimg"); nameanchor.setAttribute("href", "/product.html"); deletebutton.setAttribute("type", "button"); deletebutton.setAttribute("id", docID); nametag.textContent = doc.data().Product; location.textContent = doc.data().Location; description.textContent = doc.data().Description; price.textContent = doc.data().Price; stock.textContent = "Currently in stock"; deletebutton.textContent = "Delete"; mainrow.appendChild(imgcol); imgcol.appendChild(imgcontainer); imgcontainer.appendChild(img); mainrow.appendChild(desccol); desccol.appendChild(name); name.appendChild(nameanchor); nameanchor.appendChild(nametag); desccol.appendChild(location); desccol.appendChild(description); desccol.appendChild(pricestockrow); pricestockrow.appendChild(pricestockcol1); pricestockcol1.appendChild(price); pricestockrow.appendChild(pricestockcol2); pricestockcol2.appendChild(stock); desccol.appendChild(deletebutton); deletebutton.appendChild(buttonicon); productlist.appendChild(mainrow); productlist.appendChild(linebreak); }
JavaScript
get api() { return axios.create({ baseURL: `${this.haystackApiHost}`, timeout: 20000, withCredentials: false, headers: { 'Content-Type': 'application/json' } }) }
get api() { return axios.create({ baseURL: `${this.haystackApiHost}`, timeout: 20000, withCredentials: false, headers: { 'Content-Type': 'application/json' } }) }
JavaScript
function createEditor(code, explain, lessonName, currIndex, compIndex, review, past) { // RESOLVE mode let ResolveMode = ace.require("ace/mode/resolve").Mode; Range = ace.require("ace/range").Range; // Basic editor settings aceEditor = ace.edit("editor"); aceEditor.setTheme("ace/theme/chaos"); //chaos or solarized_light fontSize = 20; aceEditor.setFontSize(fontSize); aceEditor.on("change", checkEdit); // Store the content for future use editorContent = code; name = lessonName; aceEditor.session.setValue(editorContent); //$("#prev").attr("disabled", "disabled"); if(review == 'none') { document.getElementById("resultCard").style.display = "none"; } else { document.getElementById("resultCard").style.display = "block"; document.getElementById("resultsHeader").innerHTML = "Correct!"; document.getElementById("resultDetails").innerHTML = review; $("#resultCard").attr("class", "card bg-success text-white"); document.getElementById("answersCard").removeAttribute("hidden") document.getElementById("pastAnswers").innerHTML = past; $("#resetCode").attr("disabled", "disabled"); $("#checkCorrectness").attr("disabled", "disabled"); $("#explainCard").attr("disabled", "disabled"); } //add a check for if need explaination and set hasFR //hide or unhide explaination box // Set this to RESOLVE mode aceEditor.getSession().setMode(new ResolveMode()); //style = "visibility: hidden"; to hide text area element //use if statement to decide if should hide or show and if we need to check if it is full if (explain == 'MC') { hasFR = false; hasMC = true; } else if (explain == 'Text'){ hasFR = true; hasMC = false; } else if (explain == 'Both'){ hasFR = true; hasMC = true; } else { hasFR = false; hasMC = false; } if (parseInt(currIndex) < parseInt(compIndex)){ console.log("HIT") console.log("currIndex: " + currIndex + " compIndex: " + compIndex) aceEditor.setReadOnly(true) $("#resetCode").attr("disabled", "disabled"); $("#checkCorrectness").attr("disabled", "disabled"); } }
function createEditor(code, explain, lessonName, currIndex, compIndex, review, past) { // RESOLVE mode let ResolveMode = ace.require("ace/mode/resolve").Mode; Range = ace.require("ace/range").Range; // Basic editor settings aceEditor = ace.edit("editor"); aceEditor.setTheme("ace/theme/chaos"); //chaos or solarized_light fontSize = 20; aceEditor.setFontSize(fontSize); aceEditor.on("change", checkEdit); // Store the content for future use editorContent = code; name = lessonName; aceEditor.session.setValue(editorContent); //$("#prev").attr("disabled", "disabled"); if(review == 'none') { document.getElementById("resultCard").style.display = "none"; } else { document.getElementById("resultCard").style.display = "block"; document.getElementById("resultsHeader").innerHTML = "Correct!"; document.getElementById("resultDetails").innerHTML = review; $("#resultCard").attr("class", "card bg-success text-white"); document.getElementById("answersCard").removeAttribute("hidden") document.getElementById("pastAnswers").innerHTML = past; $("#resetCode").attr("disabled", "disabled"); $("#checkCorrectness").attr("disabled", "disabled"); $("#explainCard").attr("disabled", "disabled"); } //add a check for if need explaination and set hasFR //hide or unhide explaination box // Set this to RESOLVE mode aceEditor.getSession().setMode(new ResolveMode()); //style = "visibility: hidden"; to hide text area element //use if statement to decide if should hide or show and if we need to check if it is full if (explain == 'MC') { hasFR = false; hasMC = true; } else if (explain == 'Text'){ hasFR = true; hasMC = false; } else if (explain == 'Both'){ hasFR = true; hasMC = true; } else { hasFR = false; hasMC = false; } if (parseInt(currIndex) < parseInt(compIndex)){ console.log("HIT") console.log("currIndex: " + currIndex + " compIndex: " + compIndex) aceEditor.setReadOnly(true) $("#resetCode").attr("disabled", "disabled"); $("#checkCorrectness").attr("disabled", "disabled"); } }
JavaScript
function checkEdit(change) { var manager = aceEditor.getSession().getUndoManager(); // Must wait for the change to filter through the event system. There is // probably a way to catch it, but I couldn't find it. setTimeout(function () { // If it is a multiline change, including removing or adding a line break if (change.lines.length > 1) { manager.undo(true); return; } // If the line does not have "Confirm" in it somewhere // or it's not configured in the "lines". (added by the FAU team) if (typeof aceEditor.lines !== "undefined") { var rowNum = change.start.row + 1; if (!aceEditor.lines.includes(rowNum)) { manager.undo(true); return; } } else { var line = aceEditor.getSession().getLine(change.start.row); if (!line.includes("Confirm") && !line.includes("requires") && !line.includes("ensures")) { manager.undo(); return; } } // Make sure we do not collate undos. Downside: there is no real undo functionality manager.reset(); }, 0); }
function checkEdit(change) { var manager = aceEditor.getSession().getUndoManager(); // Must wait for the change to filter through the event system. There is // probably a way to catch it, but I couldn't find it. setTimeout(function () { // If it is a multiline change, including removing or adding a line break if (change.lines.length > 1) { manager.undo(true); return; } // If the line does not have "Confirm" in it somewhere // or it's not configured in the "lines". (added by the FAU team) if (typeof aceEditor.lines !== "undefined") { var rowNum = change.start.row + 1; if (!aceEditor.lines.includes(rowNum)) { manager.undo(true); return; } } else { var line = aceEditor.getSession().getLine(change.start.row); if (!line.includes("Confirm") && !line.includes("requires") && !line.includes("ensures")) { manager.undo(); return; } } // Make sure we do not collate undos. Downside: there is no real undo functionality manager.reset(); }, 0); }
JavaScript
function loadLesson(code, explain, lessonName) { editorContent = code; name = lessonName; aceEditor.session.setValue(editorContent); if (explain == 'MC') { hasFR = false; hasMC = true; } else if (explain == 'Text'){ hasFR = true; hasMC = false; } else { hasFR = true; hasMC = true; } }
function loadLesson(code, explain, lessonName) { editorContent = code; name = lessonName; aceEditor.session.setValue(editorContent); if (explain == 'MC') { hasFR = false; hasMC = true; } else if (explain == 'Text'){ hasFR = true; hasMC = false; } else { hasFR = true; hasMC = true; } }
JavaScript
function createAlertBox(hasError, message) { // New HTML Object #1: Alert Box let alertDiv = document.createElement("div"); alertDiv.setAttribute("id", "resultAlertBox"); // Change alert box color depending if it has error if (hasError) { alertDiv.setAttribute("class", "alert alert-danger alert-dismissible mb-0 fade show"); } else { alertDiv.setAttribute("class", "alert alert-secondary alert-dismissible mb-0 fade show"); } // Set other attributes alertDiv.setAttribute("role", "alert"); alertDiv.setAttribute("aria-hidden", "true"); // New HTML Object #2: Close Button let closeButton = document.createElement("button"); closeButton.setAttribute("type", "button"); closeButton.setAttribute("class", "close"); closeButton.setAttribute("data-dismiss", "alert"); closeButton.setAttribute("aria-label", "Close"); // New HTML Object #3: Close Icon let closeIconSpan = document.createElement("span"); closeIconSpan.setAttribute("aria-hidden", "true"); closeIconSpan.innerHTML = "&times;"; // Add close icon to close button closeButton.appendChild(closeIconSpan); // Add message and the close button to the alert box alertDiv.appendChild(document.createTextNode(message)); alertDiv.appendChild(closeButton); // Add the alert box to the div $("#compilerResult").append(alertDiv); }
function createAlertBox(hasError, message) { // New HTML Object #1: Alert Box let alertDiv = document.createElement("div"); alertDiv.setAttribute("id", "resultAlertBox"); // Change alert box color depending if it has error if (hasError) { alertDiv.setAttribute("class", "alert alert-danger alert-dismissible mb-0 fade show"); } else { alertDiv.setAttribute("class", "alert alert-secondary alert-dismissible mb-0 fade show"); } // Set other attributes alertDiv.setAttribute("role", "alert"); alertDiv.setAttribute("aria-hidden", "true"); // New HTML Object #2: Close Button let closeButton = document.createElement("button"); closeButton.setAttribute("type", "button"); closeButton.setAttribute("class", "close"); closeButton.setAttribute("data-dismiss", "alert"); closeButton.setAttribute("aria-label", "Close"); // New HTML Object #3: Close Icon let closeIconSpan = document.createElement("span"); closeIconSpan.setAttribute("aria-hidden", "true"); closeIconSpan.innerHTML = "&times;"; // Add close icon to close button closeButton.appendChild(closeIconSpan); // Add message and the close button to the alert box alertDiv.appendChild(document.createTextNode(message)); alertDiv.appendChild(closeButton); // Add the alert box to the div $("#compilerResult").append(alertDiv); }
JavaScript
function lock() { clearAlertBox(); // Lock the editors aceEditor.setReadOnly(true); // Disable the button and set checkCorrectness to true. $("#resetCode").attr("disabled", "disabled"); correctnessChecking = true; }
function lock() { clearAlertBox(); // Lock the editors aceEditor.setReadOnly(true); // Disable the button and set checkCorrectness to true. $("#resetCode").attr("disabled", "disabled"); correctnessChecking = true; }
JavaScript
function unlock() { // Unlock the editors aceEditor.setReadOnly(false); // No longer checkCorrectness, so enable the button again. correctnessChecking = false; $("#resetCode").removeAttr("disabled", "disabled"); // Focus on the editor. aceEditor.focus(); }
function unlock() { // Unlock the editors aceEditor.setReadOnly(false); // No longer checkCorrectness, so enable the button again. correctnessChecking = false; $("#resetCode").removeAttr("disabled", "disabled"); // Focus on the editor. aceEditor.focus(); }
JavaScript
function encode(data) { var regex1 = new RegExp(" ", "g"); var regex2 = new RegExp("/+", "g"); var content = encodeURIComponent(data); content = content.replace(regex1, "%20"); content = content.replace(regex2, "%2B"); var json = {}; json.name = "BeginToReason"; json.pkg = "User"; json.project = "Teaching_Project"; json.content = content; json.parent = "undefined"; json.type = "f"; return JSON.stringify(json) }
function encode(data) { var regex1 = new RegExp(" ", "g"); var regex2 = new RegExp("/+", "g"); var content = encodeURIComponent(data); content = content.replace(regex1, "%20"); content = content.replace(regex2, "%2B"); var json = {}; json.name = "BeginToReason"; json.pkg = "User"; json.project = "Teaching_Project"; json.content = content; json.parent = "undefined"; json.type = "f"; return JSON.stringify(json) }
JavaScript
function savePartialRecordingAPI(params, saveId, handleUploadStatusChange) { const url = API_ENDPOINT + SAVE_PARTIAL_RECORDING_API; const data = { ...("uniqueID" in params && {"uniqueID": params.uniqueID}), // eslint-disable-line }; let xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 204) { const response = JSON.parse(xhr.response); if (response.statusCode == 200) { uploadFile(params.video, response.fields, response.url, handleUploadStatusChange); saveId(response); } else { handleUploadStatusChange(false); } } else { handleUploadStatusChange(false); } } }; xhr.send(JSON.stringify(data)); }
function savePartialRecordingAPI(params, saveId, handleUploadStatusChange) { const url = API_ENDPOINT + SAVE_PARTIAL_RECORDING_API; const data = { ...("uniqueID" in params && {"uniqueID": params.uniqueID}), // eslint-disable-line }; let xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 204) { const response = JSON.parse(xhr.response); if (response.statusCode == 200) { uploadFile(params.video, response.fields, response.url, handleUploadStatusChange); saveId(response); } else { handleUploadStatusChange(false); } } else { handleUploadStatusChange(false); } } }; xhr.send(JSON.stringify(data)); }
JavaScript
function delay(duration) { return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(duration); }, duration) }); }
function delay(duration) { return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(duration); }, duration) }); }
JavaScript
function scrollToAnchor(target) { // If `target` is undefined or HashChangeEvent object, set it to window's hash. target = (typeof target === 'undefined' || typeof target === 'object') ? window.location.hash : target; // Escape colons from IDs, such as those found in Markdown footnote links. target = target.replace(/:/g, '\\:'); // If target element exists, scroll to it taking into account fixed navigation bar offset. if ($(target).length) { $('body').addClass('scrolling'); $('html, body').animate({ scrollTop: $(target).offset().top - navbar_offset }, 600, function () { $('body').removeClass('scrolling'); }); } }
function scrollToAnchor(target) { // If `target` is undefined or HashChangeEvent object, set it to window's hash. target = (typeof target === 'undefined' || typeof target === 'object') ? window.location.hash : target; // Escape colons from IDs, such as those found in Markdown footnote links. target = target.replace(/:/g, '\\:'); // If target element exists, scroll to it taking into account fixed navigation bar offset. if ($(target).length) { $('body').addClass('scrolling'); $('html, body').animate({ scrollTop: $(target).offset().top - navbar_offset }, 600, function () { $('body').removeClass('scrolling'); }); } }
JavaScript
function generateTemplateContents(id, description, title, price, image_path) { return "<li><div class='container h-100'><a href='' target='_blank'> <img src='extension/img/ALL/" + image_path + "'></a>" + "<div class='overlay'>" + "<div class='text'> " + description + "</div>" + " </div> <br>" + " <span class='text-primary pt-4'>" + title + " | " + price + "<br></span>" + " <button class='btn btn-primary add-item' item='" + id + "'>Add to cart <span class='badge badge-danger'></span></button>" + " <button class='btn btn-danger remove-item d-none' item='" + id + "'>Remove</button>" + "</div>" + " </li>" }
function generateTemplateContents(id, description, title, price, image_path) { return "<li><div class='container h-100'><a href='' target='_blank'> <img src='extension/img/ALL/" + image_path + "'></a>" + "<div class='overlay'>" + "<div class='text'> " + description + "</div>" + " </div> <br>" + " <span class='text-primary pt-4'>" + title + " | " + price + "<br></span>" + " <button class='btn btn-primary add-item' item='" + id + "'>Add to cart <span class='badge badge-danger'></span></button>" + " <button class='btn btn-danger remove-item d-none' item='" + id + "'>Remove</button>" + "</div>" + " </li>" }
JavaScript
function checkExists(data) { if (data.status !== 404) { console.log("Does Exist", data); getData(data); } else { console.log("Doesn't Exist", data); channelBarColour = "oops"; var channelNameArr = data.message.split(' "'); channelName = channelNameArr[channelNameArr.length - 1]; onlineStatus = "This channel doesn't exist!"; logo = "http://placehold.it/200x200"; //no such stream insert html here $('#channelBar').append('<div class ="row stream nosuchuser">' + '<div class="medium-3 columns">' + '<img src="' + logo + '" class="logo oops"' + '>' + '</div>' + '<div class="medium-9 columns">' + '<p class="noname">' + channelName.slice(0, -15) + '</p>' + '<p class="game">' + onlineStatus + '</p>' + '<button id = "delete">Remove</button>' + '</div>' + '</div>'); } }
function checkExists(data) { if (data.status !== 404) { console.log("Does Exist", data); getData(data); } else { console.log("Doesn't Exist", data); channelBarColour = "oops"; var channelNameArr = data.message.split(' "'); channelName = channelNameArr[channelNameArr.length - 1]; onlineStatus = "This channel doesn't exist!"; logo = "http://placehold.it/200x200"; //no such stream insert html here $('#channelBar').append('<div class ="row stream nosuchuser">' + '<div class="medium-3 columns">' + '<img src="' + logo + '" class="logo oops"' + '>' + '</div>' + '<div class="medium-9 columns">' + '<p class="noname">' + channelName.slice(0, -15) + '</p>' + '<p class="game">' + onlineStatus + '</p>' + '<button id = "delete">Remove</button>' + '</div>' + '</div>'); } }
JavaScript
function checkPropType(validator, callback) { return function (props, propName, componentName) { _propTypes.default.checkPropTypes(_defineProperty({}, propName, validator), props, 'prop', componentName); typeof callback === 'function' && callback(props, propName, componentName); }; }
function checkPropType(validator, callback) { return function (props, propName, componentName) { _propTypes.default.checkPropTypes(_defineProperty({}, propName, validator), props, 'prop', componentName); typeof callback === 'function' && callback(props, propName, componentName); }; }
JavaScript
function defaultFilterBy(option, props) { var filterBy = props.filterBy, labelKey = props.labelKey, multiple = props.multiple, selected = props.selected, text = props.text; // Don't show selected options in the menu for the multi-select case. if (multiple && selected.some(function (o) { return (0, _isEqual.default)(o, option); })) { return false; } var fields = filterBy.slice(); if ((0, _isFunction.default)(labelKey) && isMatch(text, labelKey(option), props)) { return true; } if ((0, _isString.default)(labelKey)) { // Add the `labelKey` field to the list of fields if it isn't already there. if (fields.indexOf(labelKey) === -1) { fields.unshift(labelKey); } } if ((0, _isString.default)(option)) { (0, _warn.default)(fields.length <= 1, 'You cannot filter by properties when `option` is a string.'); return isMatch(text, option, props); } return (0, _some.default)(fields, function (field) { var value = option[field]; if (!(0, _isString.default)(value)) { (0, _warn.default)(false, 'Fields passed to `filterBy` should have string values. Value will ' + 'be converted to a string; results may be unexpected.'); // Coerce to string since `toString` isn't null-safe. value = "".concat(value); } return isMatch(text, value, props); }); }
function defaultFilterBy(option, props) { var filterBy = props.filterBy, labelKey = props.labelKey, multiple = props.multiple, selected = props.selected, text = props.text; // Don't show selected options in the menu for the multi-select case. if (multiple && selected.some(function (o) { return (0, _isEqual.default)(o, option); })) { return false; } var fields = filterBy.slice(); if ((0, _isFunction.default)(labelKey) && isMatch(text, labelKey(option), props)) { return true; } if ((0, _isString.default)(labelKey)) { // Add the `labelKey` field to the list of fields if it isn't already there. if (fields.indexOf(labelKey) === -1) { fields.unshift(labelKey); } } if ((0, _isString.default)(option)) { (0, _warn.default)(fields.length <= 1, 'You cannot filter by properties when `option` is a string.'); return isMatch(text, option, props); } return (0, _some.default)(fields, function (field) { var value = option[field]; if (!(0, _isString.default)(value)) { (0, _warn.default)(false, 'Fields passed to `filterBy` should have string values. Value will ' + 'be converted to a string; results may be unexpected.'); // Coerce to string since `toString` isn't null-safe. value = "".concat(value); } return isMatch(text, value, props); }); }
JavaScript
function scrollIntoViewIfNeeded(node) { // Webkit browsers if (Element.prototype.scrollIntoViewIfNeeded) { node.scrollIntoViewIfNeeded(); return; } // FF, IE, etc. var rect = node.getBoundingClientRect(); var parent = node.parentNode; var parentRect = parent.getBoundingClientRect(); var parentComputedStyle = window.getComputedStyle(parent, null); var parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width'), 10); if (rect.top < parentRect.top || rect.bottom > parentRect.bottom) { parent.scrollTop = node.offsetTop - parent.offsetTop - parent.clientHeight / 2 - parentBorderTopWidth + node.clientHeight / 2; } }
function scrollIntoViewIfNeeded(node) { // Webkit browsers if (Element.prototype.scrollIntoViewIfNeeded) { node.scrollIntoViewIfNeeded(); return; } // FF, IE, etc. var rect = node.getBoundingClientRect(); var parent = node.parentNode; var parentRect = parent.getBoundingClientRect(); var parentComputedStyle = window.getComputedStyle(parent, null); var parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width'), 10); if (rect.top < parentRect.top || rect.bottom > parentRect.bottom) { parent.scrollTop = node.offsetTop - parent.offsetTop - parent.clientHeight / 2 - parentBorderTopWidth + node.clientHeight / 2; } }
JavaScript
function createColorValues(hex) { return { hex: hex, rgba: function rgba(alpha) { var a = alpha || 255; var rgb = hex_rgb_default()(hex); return "rgba(".concat(rgb.red, ", ").concat(rgb.green, ", ").concat(rgb.blue, ", ").concat(a, ")"); }, rgbaArray: function rgbaArray(alpha) { var a = alpha || 255; var rgb = hex_rgb_default()(hex); return [rgb.red, rgb.green, rgb.blue, a]; } }; }
function createColorValues(hex) { return { hex: hex, rgba: function rgba(alpha) { var a = alpha || 255; var rgb = hex_rgb_default()(hex); return "rgba(".concat(rgb.red, ", ").concat(rgb.green, ", ").concat(rgb.blue, ", ").concat(a, ")"); }, rgbaArray: function rgbaArray(alpha) { var a = alpha || 255; var rgb = hex_rgb_default()(hex); return [rgb.red, rgb.green, rgb.blue, a]; } }; }
JavaScript
function makeFeedback(feedback, correctness, defaults) { defaults = defaults || exports.defaults; var key = correctnessToFeedbackMap[correctness]; var feedbackType = key + 'Type'; var actualType = feedback ? (feedback[feedbackType] || 'default') : 'default'; if (actualType === 'custom') { return feedback[key]; } else if (actualType === 'none') { return undefined; } else { return defaults[correctness]; } }
function makeFeedback(feedback, correctness, defaults) { defaults = defaults || exports.defaults; var key = correctnessToFeedbackMap[correctness]; var feedbackType = key + 'Type'; var actualType = feedback ? (feedback[feedbackType] || 'default') : 'default'; if (actualType === 'custom') { return feedback[key]; } else if (actualType === 'none') { return undefined; } else { return defaults[correctness]; } }
JavaScript
function defaultCreateOutcome( question, answer, settings, numAnswers, numAnsweredCorrectly, totalCorrectAnswers, scoreFn ) { settings = settings || {}; if (numAnswers === 0) { return makeResponse('incorrect', 'warning', 0, 'answer-expected'); } if (question._uid !== answer._uid) { throw "Error - the uids must match"; } var isCorrect = totalCorrectAnswers === numAnsweredCorrectly && totalCorrectAnswers === numAnswers; var isPartiallyCorrect = !isCorrect && numAnsweredCorrectly > 0; var score = (scoreFn || defaultScoreFn)(isCorrect, isPartiallyCorrect); var response = makeResponse( isCorrect ? 'correct' : 'incorrect', correctness(isCorrect, isPartiallyCorrect), score); return response; //---------------------------------------------------- function makeResponse(correctness, correctClass, score, warningClass) { var response = {}; response.correctness = correctness; response.correctClass = correctClass; response.score = score; if (correctClass === 'partial' || correctClass === 'incorrect') { response.correctResponse = question.correctResponse; } if (settings.showFeedback) { response.feedback = makeFeedback(question.feedback, correctClass); } if (question.comments) { response.comments = question.comments; } if (warningClass) { response.warningClass = warningClass; } return response; } function defaultScoreFn(isCorrect, isPartiallyCorrect){ if (isCorrect) { return 1; } if (isPartiallyCorrect && question.allowPartialScoring) { return calcPartialScoring(question.partialScoring, numAnsweredCorrectly) / 100; } return 0; } function calcPartialScoring(partialScoring, numAnsweredCorrectly) { var partialScore = findPartialScoringScenario(partialScoring, numAnsweredCorrectly); return partialScore ? partialScore.scorePercentage : 0; } function findPartialScoringScenario(scenarios, numAnsweredCorrectly) { var scenario = _.find(scenarios, function(ps) { return ps.numberOfCorrect === numAnsweredCorrectly; }); return scenario; } }
function defaultCreateOutcome( question, answer, settings, numAnswers, numAnsweredCorrectly, totalCorrectAnswers, scoreFn ) { settings = settings || {}; if (numAnswers === 0) { return makeResponse('incorrect', 'warning', 0, 'answer-expected'); } if (question._uid !== answer._uid) { throw "Error - the uids must match"; } var isCorrect = totalCorrectAnswers === numAnsweredCorrectly && totalCorrectAnswers === numAnswers; var isPartiallyCorrect = !isCorrect && numAnsweredCorrectly > 0; var score = (scoreFn || defaultScoreFn)(isCorrect, isPartiallyCorrect); var response = makeResponse( isCorrect ? 'correct' : 'incorrect', correctness(isCorrect, isPartiallyCorrect), score); return response; //---------------------------------------------------- function makeResponse(correctness, correctClass, score, warningClass) { var response = {}; response.correctness = correctness; response.correctClass = correctClass; response.score = score; if (correctClass === 'partial' || correctClass === 'incorrect') { response.correctResponse = question.correctResponse; } if (settings.showFeedback) { response.feedback = makeFeedback(question.feedback, correctClass); } if (question.comments) { response.comments = question.comments; } if (warningClass) { response.warningClass = warningClass; } return response; } function defaultScoreFn(isCorrect, isPartiallyCorrect){ if (isCorrect) { return 1; } if (isPartiallyCorrect && question.allowPartialScoring) { return calcPartialScoring(question.partialScoring, numAnsweredCorrectly) / 100; } return 0; } function calcPartialScoring(partialScoring, numAnsweredCorrectly) { var partialScore = findPartialScoringScenario(partialScoring, numAnsweredCorrectly); return partialScore ? partialScore.scorePercentage : 0; } function findPartialScoringScenario(scenarios, numAnsweredCorrectly) { var scenario = _.find(scenarios, function(ps) { return ps.numberOfCorrect === numAnsweredCorrectly; }); return scenario; } }
JavaScript
function hourlyToWeekly($payRateVal, hoursPerWeek){ hourlyPerWeekUnrounded = $payRateVal * hoursPerWeek; hourlyPerWeek = hourlyPerWeekUnrounded.toFixed(2); return hourlyPerWeek; }
function hourlyToWeekly($payRateVal, hoursPerWeek){ hourlyPerWeekUnrounded = $payRateVal * hoursPerWeek; hourlyPerWeek = hourlyPerWeekUnrounded.toFixed(2); return hourlyPerWeek; }
JavaScript
function salaryToHourly(hoursPerYear, $payRateVal){ var salaryToHourlyRateUnrounded = $payRateVal / hoursPerYear; salaryToHourlyRate = salaryToHourlyRateUnrounded.toFixed(2); return salaryToHourlyRate; }
function salaryToHourly(hoursPerYear, $payRateVal){ var salaryToHourlyRateUnrounded = $payRateVal / hoursPerYear; salaryToHourlyRate = salaryToHourlyRateUnrounded.toFixed(2); return salaryToHourlyRate; }
JavaScript
function salaryToWeekly($payRateVal, weeksPerYear){ var salaryPerWeekUnrounded = $payRateVal / weeksPerYear; salaryPerWeek = salaryPerWeekUnrounded.toFixed(2); return salaryPerWeek; }
function salaryToWeekly($payRateVal, weeksPerYear){ var salaryPerWeekUnrounded = $payRateVal / weeksPerYear; salaryPerWeek = salaryPerWeekUnrounded.toFixed(2); return salaryPerWeek; }
JavaScript
startSelecting() { if (!shared_utils_1.isBrowser) { return; } window.addEventListener('mouseover', this.elementMouseOver, true); window.addEventListener('click', this.elementClicked, true); window.addEventListener('mouseout', this.cancelEvent, true); window.addEventListener('mouseenter', this.cancelEvent, true); window.addEventListener('mouseleave', this.cancelEvent, true); window.addEventListener('mousedown', this.cancelEvent, true); window.addEventListener('mouseup', this.cancelEvent, true); }
startSelecting() { if (!shared_utils_1.isBrowser) { return; } window.addEventListener('mouseover', this.elementMouseOver, true); window.addEventListener('click', this.elementClicked, true); window.addEventListener('mouseout', this.cancelEvent, true); window.addEventListener('mouseenter', this.cancelEvent, true); window.addEventListener('mouseleave', this.cancelEvent, true); window.addEventListener('mousedown', this.cancelEvent, true); window.addEventListener('mouseup', this.cancelEvent, true); }
JavaScript
async elementMouseOver(e) { this.cancelEvent(e); var el = e.target; if (el) { this.selectedInstance = await this.ctx.api.getElementComponent(el); } highlighter_1.unHighlight(); if (this.selectedInstance) { highlighter_1.highlight(this.selectedInstance, this.ctx); } }
async elementMouseOver(e) { this.cancelEvent(e); var el = e.target; if (el) { this.selectedInstance = await this.ctx.api.getElementComponent(el); } highlighter_1.unHighlight(); if (this.selectedInstance) { highlighter_1.highlight(this.selectedInstance, this.ctx); } }
JavaScript
async elementClicked(e) { this.cancelEvent(e); if (this.selectedInstance) { var parentInstances = await this.ctx.api.walkComponentParents(this.selectedInstance); this.ctx.bridge.send(shared_utils_1.BridgeEvents.TO_FRONT_COMPONENT_PICK, { id: this.selectedInstance.__VUE_DEVTOOLS_UID__, parentIds: parentInstances.map(i => i.__VUE_DEVTOOLS_UID__) }); } else { this.ctx.bridge.send(shared_utils_1.BridgeEvents.TO_FRONT_COMPONENT_PICK_CANCELED, null); } this.stopSelecting(); }
async elementClicked(e) { this.cancelEvent(e); if (this.selectedInstance) { var parentInstances = await this.ctx.api.walkComponentParents(this.selectedInstance); this.ctx.bridge.send(shared_utils_1.BridgeEvents.TO_FRONT_COMPONENT_PICK, { id: this.selectedInstance.__VUE_DEVTOOLS_UID__, parentIds: parentInstances.map(i => i.__VUE_DEVTOOLS_UID__) }); } else { this.ctx.bridge.send(shared_utils_1.BridgeEvents.TO_FRONT_COMPONENT_PICK_CANCELED, null); } this.stopSelecting(); }
JavaScript
bindMethods() { this.startSelecting = this.startSelecting.bind(this); this.stopSelecting = this.stopSelecting.bind(this); this.elementMouseOver = this.elementMouseOver.bind(this); this.elementClicked = this.elementClicked.bind(this); }
bindMethods() { this.startSelecting = this.startSelecting.bind(this); this.stopSelecting = this.stopSelecting.bind(this); this.elementMouseOver = this.elementMouseOver.bind(this); this.elementClicked = this.elementClicked.bind(this); }
JavaScript
function scan() { rootInstances.length = 0; var inFragment = false; var currentFragment = null; // eslint-disable-next-line no-inner-declarations function processInstance(instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root; } if (instance._isFragment) { inFragment = true; currentFragment = instance; } // respect Vue.config.devtools option var baseVue = instance.constructor; while (baseVue.super) { baseVue = baseVue.super; } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID; } rootInstances.push(instance); } return true; } } if (shared_utils_1.isBrowser) { var walkDocument = document => { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false; currentFragment = null; } return true; } var instance = node.__vue__; return processInstance(instance); }); }; walkDocument(document); var iframes = document.querySelectorAll('iframe'); for (var iframe of iframes) { try { walkDocument(iframe.contentDocument); } catch (e) { // Ignore } } } else { if (Array.isArray(shared_utils_1.target.__VUE_ROOT_INSTANCES__)) { shared_utils_1.target.__VUE_ROOT_INSTANCES__.map(processInstance); } } return rootInstances; }
function scan() { rootInstances.length = 0; var inFragment = false; var currentFragment = null; // eslint-disable-next-line no-inner-declarations function processInstance(instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root; } if (instance._isFragment) { inFragment = true; currentFragment = instance; } // respect Vue.config.devtools option var baseVue = instance.constructor; while (baseVue.super) { baseVue = baseVue.super; } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID; } rootInstances.push(instance); } return true; } } if (shared_utils_1.isBrowser) { var walkDocument = document => { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false; currentFragment = null; } return true; } var instance = node.__vue__; return processInstance(instance); }); }; walkDocument(document); var iframes = document.querySelectorAll('iframe'); for (var iframe of iframes) { try { walkDocument(iframe.contentDocument); } catch (e) { // Ignore } } } else { if (Array.isArray(shared_utils_1.target.__VUE_ROOT_INSTANCES__)) { shared_utils_1.target.__VUE_ROOT_INSTANCES__.map(processInstance); } } return rootInstances; }
JavaScript
function processProps(instance) { var props = instance.$options.props; var propsData = []; for (var key in props) { var prop = props[key]; key = shared_utils_1.camelize(key); propsData.push({ type: 'props', key, value: instance[key], meta: prop ? { type: prop.type ? getPropType(prop.type) : 'any', required: !!prop.required } : { type: 'invalid' }, editable: shared_data_1.default.editableProps }); } return propsData; }
function processProps(instance) { var props = instance.$options.props; var propsData = []; for (var key in props) { var prop = props[key]; key = shared_utils_1.camelize(key); propsData.push({ type: 'props', key, value: instance[key], meta: prop ? { type: prop.type ? getPropType(prop.type) : 'any', required: !!prop.required } : { type: 'invalid' }, editable: shared_data_1.default.editableProps }); } return propsData; }
JavaScript
function processState(instance) { var props = instance.$options.props; var getters = instance.$options.vuex && instance.$options.vuex.getters; return Object.keys(instance._data) .filter(key => (!(props && key in props) && !(getters && key in getters))) .map(key => ({ key, type: 'data', value: instance._data[key], editable: true })); }
function processState(instance) { var props = instance.$options.props; var getters = instance.$options.vuex && instance.$options.vuex.getters; return Object.keys(instance._data) .filter(key => (!(props && key in props) && !(getters && key in getters))) .map(key => ({ key, type: 'data', value: instance._data[key], editable: true })); }
JavaScript
function processComputed(instance) { var computed = []; var defs = instance.$options.computed || {}; // use for...in here because if 'computed' is not defined // on component, computed properties will be placed in prototype // and Object.keys does not include // properties from object's prototype for (var key in defs) { var def = defs[key]; var type = typeof def === 'function' && def.vuex ? 'vuex bindings' : 'computed'; // use try ... catch here because some computed properties may // throw error during its evaluation var computedProp = null; try { computedProp = { type, key, value: instance[key] }; } catch (e) { computedProp = { type, key, value: e }; } computed.push(computedProp); } return computed; }
function processComputed(instance) { var computed = []; var defs = instance.$options.computed || {}; // use for...in here because if 'computed' is not defined // on component, computed properties will be placed in prototype // and Object.keys does not include // properties from object's prototype for (var key in defs) { var def = defs[key]; var type = typeof def === 'function' && def.vuex ? 'vuex bindings' : 'computed'; // use try ... catch here because some computed properties may // throw error during its evaluation var computedProp = null; try { computedProp = { type, key, value: instance[key] }; } catch (e) { computedProp = { type, key, value: e }; } computed.push(computedProp); } return computed; }
JavaScript
function processRouteContext(instance) { try { var route = instance.$route; if (route) { var { path, query, params } = route; var value = { path, query, params }; if (route.fullPath) { value.fullPath = route.fullPath; } if (route.hash) { value.hash = route.hash; } if (route.name) { value.name = route.name; } if (route.meta) { value.meta = route.meta; } return [{ key: '$route', type: 'route', value: { _custom: { type: 'router', abstract: true, value } } }]; } } catch (e) { // Invalid $router } return []; }
function processRouteContext(instance) { try { var route = instance.$route; if (route) { var { path, query, params } = route; var value = { path, query, params }; if (route.fullPath) { value.fullPath = route.fullPath; } if (route.hash) { value.hash = route.hash; } if (route.name) { value.name = route.name; } if (route.meta) { value.meta = route.meta; } return [{ key: '$route', type: 'route', value: { _custom: { type: 'router', abstract: true, value } } }]; } } catch (e) { // Invalid $router } return []; }
JavaScript
function processObservables(instance) { var obs = instance.$observables; if (obs) { return Object.keys(obs).map(key => { return { type: 'observables', key, value: instance[key] }; }); } else { return []; } }
function processObservables(instance) { var obs = instance.$observables; if (obs) { return Object.keys(obs).map(key => { return { type: 'observables', key, value: instance[key] }; }); } else { return []; } }
JavaScript
function findQualifiedChildrenFromList(instances) { instances = instances .filter(child => !util_1.isBeingDestroyed(child)); return !filter ? instances.map(capture) : Array.prototype.concat.apply([], instances.map(findQualifiedChildren)); }
function findQualifiedChildrenFromList(instances) { instances = instances .filter(child => !util_1.isBeingDestroyed(child)); return !filter ? instances.map(capture) : Array.prototype.concat.apply([], instances.map(findQualifiedChildren)); }
JavaScript
function findQualifiedChildren(instance) { if (isQualified(instance)) { return capture(instance); } else { return findQualifiedChildrenFromList(instance.$children).concat(instance._vnode && instance._vnode.children // Find functional components in recursively in non-functional vnodes. ? flatten(instance._vnode.children.filter(child => !child.componentInstance).map(captureChild)) // Filter qualified children. .filter(instance => isQualified(instance)) : []); } }
function findQualifiedChildren(instance) { if (isQualified(instance)) { return capture(instance); } else { return findQualifiedChildrenFromList(instance.$children).concat(instance._vnode && instance._vnode.children // Find functional components in recursively in non-functional vnodes. ? flatten(instance._vnode.children.filter(child => !child.componentInstance).map(captureChild)) // Filter qualified children. .filter(instance => isQualified(instance)) : []); } }
JavaScript
function capture(instance, index, list) { var _a, _b; if (instance.__VUE_DEVTOOLS_FUNCTIONAL_LEGACY__) { instance = instance.vnode; } if (instance.$options && instance.$options.abstract && instance._vnode && instance._vnode.componentInstance) { instance = instance._vnode.componentInstance; } if ((_b = (_a = instance.$options) === null || _a === void 0 ? void 0 : _a.devtools) === null || _b === void 0 ? void 0 : _b.hide) { return; } // Functional component. if (instance.fnContext && !instance.componentInstance) { var contextUid = instance.fnContext.__VUE_DEVTOOLS_UID__; var id = functionalIds.get(contextUid); if (id == null) { id = 0; } else { id++; } functionalIds.set(contextUid, id); var functionalId = contextUid + ':functional:' + id; markFunctional(functionalId, instance); var children$1 = (instance.children ? instance.children.map(child => child.fnContext ? captureChild(child) : child.componentInstance ? capture(child.componentInstance) : undefined) // router-view has both fnContext and componentInstance on vnode. : instance.componentInstance ? [capture(instance.componentInstance)] : []).filter(Boolean); return { uid: functionalId, id: functionalId, tags: [ { label: 'functional', textColor: 0x555555, backgroundColor: 0xeeeeee } ], name: util_1.getInstanceName(instance), renderKey: util_1.getRenderKey(instance.key), children: children$1, hasChildren: !!children$1.length, inactive: false, isFragment: false // TODO: Check what is it for. }; } // instance._uid is not reliable in devtools as there // may be 2 roots with same _uid which causes unexpected // behaviour instance.__VUE_DEVTOOLS_UID__ = util_1.getUniqueId(instance); // Dedupe if (captureIds.has(instance.__VUE_DEVTOOLS_UID__)) { return; } else { captureIds.set(instance.__VUE_DEVTOOLS_UID__, undefined); } mark(instance); var name = util_1.getInstanceName(instance); var children = getInternalInstanceChildren(instance) .filter(child => !util_1.isBeingDestroyed(child)) .map(capture) .filter(Boolean); var ret = { uid: instance._uid, id: instance.__VUE_DEVTOOLS_UID__, name, renderKey: util_1.getRenderKey(instance.$vnode ? instance.$vnode.key : null), inactive: !!instance._inactive, isFragment: !!instance._isFragment, children, hasChildren: !!children.length, tags: [], meta: {} }; if (instance._vnode && instance._vnode.children) { ret.children = ret.children.concat(flatten(instance._vnode.children.map(captureChild)) .filter(Boolean)); ret.hasChildren = !!ret.children.length; } // record screen position to ensure correct ordering if ((!list || list.length > 1) && !instance._inactive) { var rect = el_1.getInstanceOrVnodeRect(instance); ret.positionTop = rect ? rect.top : Infinity; } else { ret.positionTop = Infinity; } // check if instance is available in console var consoleId = consoleBoundInstances.indexOf(instance.__VUE_DEVTOOLS_UID__); ret.consoleId = consoleId > -1 ? '$vm' + consoleId : null; // check router view var isRouterView2 = instance.$vnode && instance.$vnode.data.routerView; if (instance._routerView || isRouterView2) { ret.isRouterView = true; if (!instance._inactive && instance.$route) { var matched = instance.$route.matched; var depth = isRouterView2 ? instance.$vnode.data.routerViewDepth : instance._routerView.depth; ret.meta.matchedRouteSegment = matched && matched[depth] && (isRouterView2 ? matched[depth].path : matched[depth].handler.path); } ret.tags.push({ label: `router-view${ret.meta.matchedRouteSegment ? `: ${ret.meta.matchedRouteSegment}` : ''}`, textColor: 0x000000, backgroundColor: 0xff8344 }); } return ret; }
function capture(instance, index, list) { var _a, _b; if (instance.__VUE_DEVTOOLS_FUNCTIONAL_LEGACY__) { instance = instance.vnode; } if (instance.$options && instance.$options.abstract && instance._vnode && instance._vnode.componentInstance) { instance = instance._vnode.componentInstance; } if ((_b = (_a = instance.$options) === null || _a === void 0 ? void 0 : _a.devtools) === null || _b === void 0 ? void 0 : _b.hide) { return; } // Functional component. if (instance.fnContext && !instance.componentInstance) { var contextUid = instance.fnContext.__VUE_DEVTOOLS_UID__; var id = functionalIds.get(contextUid); if (id == null) { id = 0; } else { id++; } functionalIds.set(contextUid, id); var functionalId = contextUid + ':functional:' + id; markFunctional(functionalId, instance); var children$1 = (instance.children ? instance.children.map(child => child.fnContext ? captureChild(child) : child.componentInstance ? capture(child.componentInstance) : undefined) // router-view has both fnContext and componentInstance on vnode. : instance.componentInstance ? [capture(instance.componentInstance)] : []).filter(Boolean); return { uid: functionalId, id: functionalId, tags: [ { label: 'functional', textColor: 0x555555, backgroundColor: 0xeeeeee } ], name: util_1.getInstanceName(instance), renderKey: util_1.getRenderKey(instance.key), children: children$1, hasChildren: !!children$1.length, inactive: false, isFragment: false // TODO: Check what is it for. }; } // instance._uid is not reliable in devtools as there // may be 2 roots with same _uid which causes unexpected // behaviour instance.__VUE_DEVTOOLS_UID__ = util_1.getUniqueId(instance); // Dedupe if (captureIds.has(instance.__VUE_DEVTOOLS_UID__)) { return; } else { captureIds.set(instance.__VUE_DEVTOOLS_UID__, undefined); } mark(instance); var name = util_1.getInstanceName(instance); var children = getInternalInstanceChildren(instance) .filter(child => !util_1.isBeingDestroyed(child)) .map(capture) .filter(Boolean); var ret = { uid: instance._uid, id: instance.__VUE_DEVTOOLS_UID__, name, renderKey: util_1.getRenderKey(instance.$vnode ? instance.$vnode.key : null), inactive: !!instance._inactive, isFragment: !!instance._isFragment, children, hasChildren: !!children.length, tags: [], meta: {} }; if (instance._vnode && instance._vnode.children) { ret.children = ret.children.concat(flatten(instance._vnode.children.map(captureChild)) .filter(Boolean)); ret.hasChildren = !!ret.children.length; } // record screen position to ensure correct ordering if ((!list || list.length > 1) && !instance._inactive) { var rect = el_1.getInstanceOrVnodeRect(instance); ret.positionTop = rect ? rect.top : Infinity; } else { ret.positionTop = Infinity; } // check if instance is available in console var consoleId = consoleBoundInstances.indexOf(instance.__VUE_DEVTOOLS_UID__); ret.consoleId = consoleId > -1 ? '$vm' + consoleId : null; // check router view var isRouterView2 = instance.$vnode && instance.$vnode.data.routerView; if (instance._routerView || isRouterView2) { ret.isRouterView = true; if (!instance._inactive && instance.$route) { var matched = instance.$route.matched; var depth = isRouterView2 ? instance.$vnode.data.routerViewDepth : instance._routerView.depth; ret.meta.matchedRouteSegment = matched && matched[depth] && (isRouterView2 ? matched[depth].path : matched[depth].handler.path); } ret.tags.push({ label: `router-view${ret.meta.matchedRouteSegment ? `: ${ret.meta.matchedRouteSegment}` : ''}`, textColor: 0x000000, backgroundColor: 0xff8344 }); } return ret; }
JavaScript
function processProps(instance) { var propsData = []; var propDefinitions = instance.type.props; var loop = function ( key ) { var propDefinition = propDefinitions ? propDefinitions[key] : null; key = shared_utils_1.camelize(key); propsData.push({ type: 'props', key, value: util_2.returnError(() => instance.props[key]), meta: propDefinition ? Object.assign({}, {type: propDefinition.type ? getPropType(propDefinition.type) : 'any', required: !!propDefinition.required}, propDefinition.default != null ? { default: propDefinition.default.toString() } : {}) : { type: 'invalid' }, editable: shared_data_1.default.editableProps }); }; for (var key in instance.props) loop( key ); return propsData; }
function processProps(instance) { var propsData = []; var propDefinitions = instance.type.props; var loop = function ( key ) { var propDefinition = propDefinitions ? propDefinitions[key] : null; key = shared_utils_1.camelize(key); propsData.push({ type: 'props', key, value: util_2.returnError(() => instance.props[key]), meta: propDefinition ? Object.assign({}, {type: propDefinition.type ? getPropType(propDefinition.type) : 'any', required: !!propDefinition.required}, propDefinition.default != null ? { default: propDefinition.default.toString() } : {}) : { type: 'invalid' }, editable: shared_data_1.default.editableProps }); }; for (var key in instance.props) loop( key ); return propsData; }
JavaScript
function processState(instance) { var type = instance.type; var props = type.props; var getters = type.vuex && type.vuex.getters; var computedDefs = type.computed; var data = Object.assign({}, instance.data, instance.renderContext); return Object.keys(data) .filter(key => (!(props && key in props) && !(getters && key in getters) && !(computedDefs && key in computedDefs))) .map(key => ({ key, type: 'data', value: util_2.returnError(() => data[key]), editable: true })); }
function processState(instance) { var type = instance.type; var props = type.props; var getters = type.vuex && type.vuex.getters; var computedDefs = type.computed; var data = Object.assign({}, instance.data, instance.renderContext); return Object.keys(data) .filter(key => (!(props && key in props) && !(getters && key in getters) && !(computedDefs && key in computedDefs))) .map(key => ({ key, type: 'data', value: util_2.returnError(() => data[key]), editable: true })); }
JavaScript
async findQualifiedChildrenFromList(instances, depth) { instances = instances .filter(child => { var _a; return !util_1.isBeingDestroyed(child) && !((_a = child.type.devtools) === null || _a === void 0 ? void 0 : _a.hide); }); if (!this.componentFilter.filter) { return Promise.all(instances.map((child, index, list) => this.capture(child, list, depth))); } else { return Array.prototype.concat.apply([], await Promise.all(instances.map(i => this.findQualifiedChildren(i, depth)))); } }
async findQualifiedChildrenFromList(instances, depth) { instances = instances .filter(child => { var _a; return !util_1.isBeingDestroyed(child) && !((_a = child.type.devtools) === null || _a === void 0 ? void 0 : _a.hide); }); if (!this.componentFilter.filter) { return Promise.all(instances.map((child, index, list) => this.capture(child, list, depth))); } else { return Array.prototype.concat.apply([], await Promise.all(instances.map(i => this.findQualifiedChildren(i, depth)))); } }
JavaScript
mark(instance) { var instanceMap = this.ctx.currentAppRecord.instanceMap; if (!instanceMap.has(instance.__VUE_DEVTOOLS_UID__)) { instanceMap.set(instance.__VUE_DEVTOOLS_UID__, instance); } }
mark(instance) { var instanceMap = this.ctx.currentAppRecord.instanceMap; if (!instanceMap.has(instance.__VUE_DEVTOOLS_UID__)) { instanceMap.set(instance.__VUE_DEVTOOLS_UID__, instance); } }
JavaScript
cache(data, factory) { var cached = this.map.get(data); if (cached) { return cached; } else { var result = factory(data); this.map.set(data, result); return result; } }
cache(data, factory) { var cached = this.map.get(data); if (cached) { return cached; } else { var result = factory(data); this.map.set(data, result); return result; } }
JavaScript
function deriveContributionStats(contributionData) { // Some variables var longestStreak = 0; var currentStreak = 0; var lastDay = '0-0-0'; // Reduce the total number of contributions to a single integer const totalContributions = contributionData.reduce(function (last, current, index) { // Calculate the exptected day to continue the streak var expectedDay = new Date(lastDay); expectedDay.setDate(expectedDay.getDate() + 1); // Increment day by 1 const year = expectedDay.getFullYear(); var month = expectedDay.getMonth() + 1; // The month starts from zero var day = expectedDay.getDate(); // Left-pad for noobs if (month < 10) { month = '0' + month; } if (day < 10) { day = '0' + day; } expectedDay = ( year + '-' + month + '-' + day ); // If the streak was continued, increment, else reset if (expectedDay === current.dataDate) { currentStreak++; } else { currentStreak = 0; } if (currentStreak > longestStreak) { longestStreak = currentStreak; } // Update the last day lastDay = current.dataDate; return last + current.dataContributionCount; }, 0); return { totalContributions: totalContributions, longestStreak: longestStreak + 1, currentStreak: currentStreak + 1 }; }
function deriveContributionStats(contributionData) { // Some variables var longestStreak = 0; var currentStreak = 0; var lastDay = '0-0-0'; // Reduce the total number of contributions to a single integer const totalContributions = contributionData.reduce(function (last, current, index) { // Calculate the exptected day to continue the streak var expectedDay = new Date(lastDay); expectedDay.setDate(expectedDay.getDate() + 1); // Increment day by 1 const year = expectedDay.getFullYear(); var month = expectedDay.getMonth() + 1; // The month starts from zero var day = expectedDay.getDate(); // Left-pad for noobs if (month < 10) { month = '0' + month; } if (day < 10) { day = '0' + day; } expectedDay = ( year + '-' + month + '-' + day ); // If the streak was continued, increment, else reset if (expectedDay === current.dataDate) { currentStreak++; } else { currentStreak = 0; } if (currentStreak > longestStreak) { longestStreak = currentStreak; } // Update the last day lastDay = current.dataDate; return last + current.dataContributionCount; }, 0); return { totalContributions: totalContributions, longestStreak: longestStreak + 1, currentStreak: currentStreak + 1 }; }
JavaScript
function formatReturnData(contributionData, statsData) { var commitsToday = getCommitsToday(contributionData); var returnData = {contributionData: contributionData, statsData: statsData, commitsToday: commitsToday}; return commitsToday == null ? null : returnData; }
function formatReturnData(contributionData, statsData) { var commitsToday = getCommitsToday(contributionData); var returnData = {contributionData: contributionData, statsData: statsData, commitsToday: commitsToday}; return commitsToday == null ? null : returnData; }
JavaScript
function scrapeContributionData(html, callback) { $ = cheerio.load(html); var commitDataArray = []; $('rect').each(function(index, commitData) { // Look for our contribtion data var dataContributionCount = parseInt(commitData.attribs['data-count']), dataDate = commitData.attribs['data-date'], commitDataObj = {}; // Validate it contains data if (dataContributionCount && dataDate) { commitDataObj.dataContributionCount = dataContributionCount; commitDataObj.dataDate = dataDate; commitDataArray.push(commitDataObj); } }); // Validate it contains data before sending if (commitDataArray.length > 0) { callback(commitDataArray); } else { // If it fails validation return null callback(null); } }
function scrapeContributionData(html, callback) { $ = cheerio.load(html); var commitDataArray = []; $('rect').each(function(index, commitData) { // Look for our contribtion data var dataContributionCount = parseInt(commitData.attribs['data-count']), dataDate = commitData.attribs['data-date'], commitDataObj = {}; // Validate it contains data if (dataContributionCount && dataDate) { commitDataObj.dataContributionCount = dataContributionCount; commitDataObj.dataDate = dataDate; commitDataArray.push(commitDataObj); } }); // Validate it contains data before sending if (commitDataArray.length > 0) { callback(commitDataArray); } else { // If it fails validation return null callback(null); } }
JavaScript
function dayOfYear(date) { var now = new Date(date); var start = new Date(now.getFullYear(), 0, 0); var diff = now - start; var oneDay = 1000 * 60 * 60 * 24; var day = Math.floor(diff / oneDay); return day; }
function dayOfYear(date) { var now = new Date(date); var start = new Date(now.getFullYear(), 0, 0); var diff = now - start; var oneDay = 1000 * 60 * 60 * 24; var day = Math.floor(diff / oneDay); return day; }
JavaScript
function buildTeam() { inquirer.prompt({ type: "list", name: "choice", message: "What do you wanna do?", choices: ["Add New Manager", "Add New Engineer", "Add New Intern", "Quit"] }).then(function ({ choice }) { switch (choice) { case "Add New Manager": createManager(); break; case "Add New Engineer": createEngineer(); break; case "Add New Intern": createIntern(); break; default: // May need a call to if no one is on team, force edge case of add someone console.log("Team Added to board") console.table(myEmployees); // call rendering using myEmployees Array let myTeamHTML = render(myEmployees); fs.writeFile('./output/team.html', myTeamHTML, (err) => { if(err) throw err; console.log("File Saved"); }); break; } }) }
function buildTeam() { inquirer.prompt({ type: "list", name: "choice", message: "What do you wanna do?", choices: ["Add New Manager", "Add New Engineer", "Add New Intern", "Quit"] }).then(function ({ choice }) { switch (choice) { case "Add New Manager": createManager(); break; case "Add New Engineer": createEngineer(); break; case "Add New Intern": createIntern(); break; default: // May need a call to if no one is on team, force edge case of add someone console.log("Team Added to board") console.table(myEmployees); // call rendering using myEmployees Array let myTeamHTML = render(myEmployees); fs.writeFile('./output/team.html', myTeamHTML, (err) => { if(err) throw err; console.log("File Saved"); }); break; } }) }
JavaScript
function createManager() { inquirer.prompt([ { type: "input", message: "Enter Manager's name: ", name: "name" }, { type: "input", message: "Enter Manager's email: ", name: "email" }, { type: "input", message: "Enter Manager's office phone: ", name: "officePhone" } ]).then(function (answers) { // Take answers and make new Manager object, push it into the myEmployees Array myEmployees.push(new Manager(answers.name, idHolder, answers.email, answers.officePhone)); // increment for new id number for next employee idHolder++; buildTeam(); }) }
function createManager() { inquirer.prompt([ { type: "input", message: "Enter Manager's name: ", name: "name" }, { type: "input", message: "Enter Manager's email: ", name: "email" }, { type: "input", message: "Enter Manager's office phone: ", name: "officePhone" } ]).then(function (answers) { // Take answers and make new Manager object, push it into the myEmployees Array myEmployees.push(new Manager(answers.name, idHolder, answers.email, answers.officePhone)); // increment for new id number for next employee idHolder++; buildTeam(); }) }
JavaScript
function createEngineer() { inquirer.prompt([ { type: "input", message: "Enter Engineer's name: ", name: "name" }, { type: "input", message: "Enter Engineer's email: ", name: "email" }, { type: "input", message: "Enter Engineer's Github: ", name: "github" } ]).then(function (answers) { // Take answers and make new Engineer object, push it into the myEmployees Array myEmployees.push(new Engineer(answers.name, idHolder, answers.email, answers.github)); // increment for new id number for next employee idHolder++; buildTeam(); }) }
function createEngineer() { inquirer.prompt([ { type: "input", message: "Enter Engineer's name: ", name: "name" }, { type: "input", message: "Enter Engineer's email: ", name: "email" }, { type: "input", message: "Enter Engineer's Github: ", name: "github" } ]).then(function (answers) { // Take answers and make new Engineer object, push it into the myEmployees Array myEmployees.push(new Engineer(answers.name, idHolder, answers.email, answers.github)); // increment for new id number for next employee idHolder++; buildTeam(); }) }
JavaScript
function createIntern() { inquirer.prompt([ { type: "input", message: "Enter Intern's name: ", name: "name" }, { type: "input", message: "Enter Intern's email: ", name: "email" }, { type: "input", message: "Enter Intern's school: ", name: "school" } ]).then(function (answers) { // Take answers and make new Intern object, push it into the myEmployees Array myEmployees.push(new Intern(answers.name, idHolder, answers.email, answers.school)); // increment for new id number for next employee idHolder++; buildTeam(); }) }
function createIntern() { inquirer.prompt([ { type: "input", message: "Enter Intern's name: ", name: "name" }, { type: "input", message: "Enter Intern's email: ", name: "email" }, { type: "input", message: "Enter Intern's school: ", name: "school" } ]).then(function (answers) { // Take answers and make new Intern object, push it into the myEmployees Array myEmployees.push(new Intern(answers.name, idHolder, answers.email, answers.school)); // increment for new id number for next employee idHolder++; buildTeam(); }) }
JavaScript
function env(data) { //create key pairs let privateKeyPath = path.join(__dirname, "..", "keys", "private.key"); let publicKeyPath = path.join(__dirname, "..", "keys", "public.key"); let envPath = path.join(__dirname, "..", ".env"); var pair = keypair(); try { if (!fs.existsSync("key")) { fs.mkdirSync("keys"); fs.writeFileSync(privateKeyPath, pair.private); fs.writeFileSync(publicKeyPath, pair.public); //add mongodb user to env file fs.appendFileSync(envPath, '\nDB_USER=' + data.user + '\nDB_PASSWORD=' + data.password + '\nDB_PORT=' + data.port + '\nDB_ADDRESS=' + data.address); initializeDatabase(data); } else { log(chalk.yellow("Keys folder exists. If this is a new install, delete the key folder")); } } catch (e) { log(chalk.red("Error occured writing/creating to 'keys' folder: " + e)) } }
function env(data) { //create key pairs let privateKeyPath = path.join(__dirname, "..", "keys", "private.key"); let publicKeyPath = path.join(__dirname, "..", "keys", "public.key"); let envPath = path.join(__dirname, "..", ".env"); var pair = keypair(); try { if (!fs.existsSync("key")) { fs.mkdirSync("keys"); fs.writeFileSync(privateKeyPath, pair.private); fs.writeFileSync(publicKeyPath, pair.public); //add mongodb user to env file fs.appendFileSync(envPath, '\nDB_USER=' + data.user + '\nDB_PASSWORD=' + data.password + '\nDB_PORT=' + data.port + '\nDB_ADDRESS=' + data.address); initializeDatabase(data); } else { log(chalk.yellow("Keys folder exists. If this is a new install, delete the key folder")); } } catch (e) { log(chalk.red("Error occured writing/creating to 'keys' folder: " + e)) } }
JavaScript
function initializeDatabase(data) { //create role createRole(getRoles(), createAppOwner); //deleteInstallFile(); }
function initializeDatabase(data) { //create role createRole(getRoles(), createAppOwner); //deleteInstallFile(); }
JavaScript
function checkInstallFile(req, res, next) { let installFile = path.join(__dirname, "..", "install"); if (fs.existsSync(installFile)) { if (debug) console.log("Installation file exist"); res.redirect("/install"); } else { if (debug) console.log("Installation file does not exist"); next(); } }
function checkInstallFile(req, res, next) { let installFile = path.join(__dirname, "..", "install"); if (fs.existsSync(installFile)) { if (debug) console.log("Installation file exist"); res.redirect("/install"); } else { if (debug) console.log("Installation file does not exist"); next(); } }
JavaScript
function installValid(req, res, next) { let installFile = path.join(__dirname, "..", "install"); if (fs.existsSync(installFile)) { if (debug) console.log("Installation file exist"); next(); } else { res.redirect("/"); } }
function installValid(req, res, next) { let installFile = path.join(__dirname, "..", "install"); if (fs.existsSync(installFile)) { if (debug) console.log("Installation file exist"); next(); } else { res.redirect("/"); } }
JavaScript
function sendto_handlecontextmenu_listener(event) { if (event.target) { // look for an enclosing anchor tag to get the url var data = sendto_findlink(event.target); // otherwise look in the document for a feed url if (!data) { var links = document.getElementsByTagName('link'); // prefer atom non comment feed first // prefer any non comment feed next // lastly take whatever feed we find for (var p=1; p <= 3; p++) { for (var i=0; i < links.length; i++) { var link = links[i]; if (link.getAttribute('rel').indexOf('alternate') >= 0) { var linkType = link.getAttribute('type'); if (!linkType) continue; linkType = linkType.toLowerCase(); var href = link.getAttribute('href'); if (!href) continue; var title = link.getAttribute('title'); if (!title) title = ""; title = title.toLowerCase(); if (linkType.indexOf('rss') >= 0 || linkType.indexOf('atom') >= 0 || linkType.indexOf('xml') >= 0) { if (p === 1 && linkType.indexOf('atom') >= 0 && title.indexOf('comment') < 0) { data = href; break; } else if (p === 2 && title.indexOf('comment') < 0) { data = href; break; } else if (p === 3) { data = href; break; } } } } } } // if no url found then use page url if (!data || data.length <= 2) data = location.href; // if still no url then done if (!data || data.length <= 2) return; if (data.indexOf('http://') === 0 || data.indexOf('https://') === 0 || data.indexOf('feed://') === 0 || data.indexOf('rss://') === 0) { // we have a full url so good to go } else if (data.substring(8).indexOf('://') > 0) { // non http URL so ignore it return; } else if (data.indexOf('/') === 0) { // we have a protocol relative url so add protocol and host back in front data = location.protocol + '://' + location.host + url; } else { // relative url so add protocol and base back var firstSlash = location.href.substring(8).indexOf('/'); data = location.href.substring(0, 8 + firstSlash) + url; } console.log("sendto_handlecontextmenu_listener: " + data); safari.self.tab.setContextMenuEventUserInfo(event, data); } }
function sendto_handlecontextmenu_listener(event) { if (event.target) { // look for an enclosing anchor tag to get the url var data = sendto_findlink(event.target); // otherwise look in the document for a feed url if (!data) { var links = document.getElementsByTagName('link'); // prefer atom non comment feed first // prefer any non comment feed next // lastly take whatever feed we find for (var p=1; p <= 3; p++) { for (var i=0; i < links.length; i++) { var link = links[i]; if (link.getAttribute('rel').indexOf('alternate') >= 0) { var linkType = link.getAttribute('type'); if (!linkType) continue; linkType = linkType.toLowerCase(); var href = link.getAttribute('href'); if (!href) continue; var title = link.getAttribute('title'); if (!title) title = ""; title = title.toLowerCase(); if (linkType.indexOf('rss') >= 0 || linkType.indexOf('atom') >= 0 || linkType.indexOf('xml') >= 0) { if (p === 1 && linkType.indexOf('atom') >= 0 && title.indexOf('comment') < 0) { data = href; break; } else if (p === 2 && title.indexOf('comment') < 0) { data = href; break; } else if (p === 3) { data = href; break; } } } } } } // if no url found then use page url if (!data || data.length <= 2) data = location.href; // if still no url then done if (!data || data.length <= 2) return; if (data.indexOf('http://') === 0 || data.indexOf('https://') === 0 || data.indexOf('feed://') === 0 || data.indexOf('rss://') === 0) { // we have a full url so good to go } else if (data.substring(8).indexOf('://') > 0) { // non http URL so ignore it return; } else if (data.indexOf('/') === 0) { // we have a protocol relative url so add protocol and host back in front data = location.protocol + '://' + location.host + url; } else { // relative url so add protocol and base back var firstSlash = location.href.substring(8).indexOf('/'); data = location.href.substring(0, 8 + firstSlash) + url; } console.log("sendto_handlecontextmenu_listener: " + data); safari.self.tab.setContextMenuEventUserInfo(event, data); } }
JavaScript
function typeNameToId(typeName) { var typeNameIndex = aliasMappingArray.indexOf(typeName); return (typeNameIndex !== -1 ? typeMappingArray[typeNameIndex] : xtype.NONE); }
function typeNameToId(typeName) { var typeNameIndex = aliasMappingArray.indexOf(typeName); return (typeNameIndex !== -1 ? typeMappingArray[typeNameIndex] : xtype.NONE); }
JavaScript
function typeIdToName(typeId) { var typeIdIndex = typeMappingArray.indexOf(typeId); if (typeIdIndex === -1) { typeIdIndex = typeMappingArray.indexOf(xtype.NONE); } return aliasMappingArray[typeIdIndex]; }
function typeIdToName(typeId) { var typeIdIndex = typeMappingArray.indexOf(typeId); if (typeIdIndex === -1) { typeIdIndex = typeMappingArray.indexOf(xtype.NONE); } return aliasMappingArray[typeIdIndex]; }
JavaScript
function typeComposition(type) { var typeId = (typeof type === 'string' ? typeNameToId(type) : type), composition = []; if (typeof typeId === 'function') { // instance type composition.push(typeId); } else if (typeof typeId === 'number') { typeIds().forEach(function(candidateTypeId) { if (!isCompositeType(candidateTypeId) && (typeId & candidateTypeId) > 0) { composition.push(typeIdToName(candidateTypeId)); } }); } return composition; }
function typeComposition(type) { var typeId = (typeof type === 'string' ? typeNameToId(type) : type), composition = []; if (typeof typeId === 'function') { // instance type composition.push(typeId); } else if (typeof typeId === 'number') { typeIds().forEach(function(candidateTypeId) { if (!isCompositeType(candidateTypeId) && (typeId & candidateTypeId) > 0) { composition.push(typeIdToName(candidateTypeId)); } }); } return composition; }
JavaScript
function typeDefaultName(type) { var typeAlias = (typeof type !== 'string' ? typeIdToName(type) : type); return (aliasToNameMapping[typeAlias] || aliasToNameMapping[typeIdToName(xtype.NONE)]); }
function typeDefaultName(type) { var typeAlias = (typeof type !== 'string' ? typeIdToName(type) : type); return (aliasToNameMapping[typeAlias] || aliasToNameMapping[typeIdToName(xtype.NONE)]); }
JavaScript
function typeFriendlyName(type) { var friendlyNames = [], types = (Array.isArray(type) ? type : [type]); types.forEach(function(suppliedType) { var typeAlias = (typeof suppliedType !== 'string' ? typeIdToName(suppliedType) : suppliedType), friendlyName = aliasToFriendlyNameMapping[typeAlias] || aliasToFriendlyNameMapping[typeIdToName(xtype.NONE)]; friendlyNames.push(friendlyName); }); return friendlyNames.join(', '); }
function typeFriendlyName(type) { var friendlyNames = [], types = (Array.isArray(type) ? type : [type]); types.forEach(function(suppliedType) { var typeAlias = (typeof suppliedType !== 'string' ? typeIdToName(suppliedType) : suppliedType), friendlyName = aliasToFriendlyNameMapping[typeAlias] || aliasToFriendlyNameMapping[typeIdToName(xtype.NONE)]; friendlyNames.push(friendlyName); }); return friendlyNames.join(', '); }
JavaScript
function isType(item, types) { var compositeType = (typeof types === 'number') ? (ANY_TYPE & types) : (typeof types === 'string' && typeListStringToTypeIdCache[types] !== undefined) ? typeListStringToTypeIdCache[types] : getCompositeType(types, item); return (typeof compositeType === 'function') || // Item is a specified instance type (typeof compositeType === 'object') || // Item is a specified custom type !!(getBaseType(item, compositeType)); }
function isType(item, types) { var compositeType = (typeof types === 'number') ? (ANY_TYPE & types) : (typeof types === 'string' && typeListStringToTypeIdCache[types] !== undefined) ? typeListStringToTypeIdCache[types] : getCompositeType(types, item); return (typeof compositeType === 'function') || // Item is a specified instance type (typeof compositeType === 'object') || // Item is a specified custom type !!(getBaseType(item, compositeType)); }
JavaScript
function which(item, types) { types = (typeof types === 'string') ? types.split(typeDelimiterRegExp) : (!isArray(types) ? [types] : types); var typeCount = types.length, typeIndex; for (typeIndex = 0; typeIndex < typeCount; typeIndex++) { if (isType(item, types[typeIndex])) { return types[typeIndex]; } } return typeToAliasMapping[NONE_TYPE]; }
function which(item, types) { types = (typeof types === 'string') ? types.split(typeDelimiterRegExp) : (!isArray(types) ? [types] : types); var typeCount = types.length, typeIndex; for (typeIndex = 0; typeIndex < typeCount; typeIndex++) { if (isType(item, types[typeIndex])) { return types[typeIndex]; } } return typeToAliasMapping[NONE_TYPE]; }
JavaScript
function buildAliasMappings() { var typeAliasMapping = newObj(), aliasTypeMapping = newObj(), nameAliasMapping = newObj(), usedAliases = newObj(); objKeys(typeToValueMapping).forEach(function(typeName) { var typeValue = typeToValueMapping[typeName]; var aliasName = (activeNameScheme ? activeNameScheme[typeName] : typeName); aliasName = ((typeof aliasName === 'string' && aliasName.length > 0) ? aliasName : typeName); if (aliasName in usedAliases) { throwError('Type name conflict: "' + aliasName + '" is aliased to "' + typeName + '" and "' + usedAliases[aliasName] + '"'); } if (typeof typeValue === 'number') { typeAliasMapping[typeValue] = aliasName; // Type Ids used only for built-in simple and extended types (with numeric Ids) } aliasTypeMapping[aliasName] = typeValue; nameAliasMapping[typeName] = aliasName; usedAliases[aliasName] = typeName; }); typeToAliasMapping = typeAliasMapping; aliasToTypeMapping = aliasTypeMapping; nameToAliasMapping = nameAliasMapping; isAliasMode = !!activeNameScheme; clearTypeListStringCache(); }
function buildAliasMappings() { var typeAliasMapping = newObj(), aliasTypeMapping = newObj(), nameAliasMapping = newObj(), usedAliases = newObj(); objKeys(typeToValueMapping).forEach(function(typeName) { var typeValue = typeToValueMapping[typeName]; var aliasName = (activeNameScheme ? activeNameScheme[typeName] : typeName); aliasName = ((typeof aliasName === 'string' && aliasName.length > 0) ? aliasName : typeName); if (aliasName in usedAliases) { throwError('Type name conflict: "' + aliasName + '" is aliased to "' + typeName + '" and "' + usedAliases[aliasName] + '"'); } if (typeof typeValue === 'number') { typeAliasMapping[typeValue] = aliasName; // Type Ids used only for built-in simple and extended types (with numeric Ids) } aliasTypeMapping[aliasName] = typeValue; nameAliasMapping[typeName] = aliasName; usedAliases[aliasName] = typeName; }); typeToAliasMapping = typeAliasMapping; aliasToTypeMapping = aliasTypeMapping; nameToAliasMapping = nameAliasMapping; isAliasMode = !!activeNameScheme; clearTypeListStringCache(); }
JavaScript
function defineType(typeName, typeDefinition, hostObj) { if (typeName in typeToValueMapping) { throwError('Cannot define type \'' + typeName + '\' - type already defined'); } typeToValueMapping[typeName] = typeDefinition; if (typeof typeDefinition === 'number') { Object.defineProperty(hostObj, typeName.toUpperCase(), { value: typeToValueMapping[typeName], enumerable: true, writable: false, configurable: false }); } var typeMethodName = getTypeMethodName(typeName); var typeCheckFunction = function(item) { return isType(item, (typeToValueMapping[typeName] || typeName)); }; hostObj[typeMethodName] = typeCheckFunction; hostObj.not[typeMethodName] = function(value) { return !typeCheckFunction(value); }; hostObj.any[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, true, undefined, true); hostObj.all[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, undefined, true, false); hostObj.some[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, true, true, true); hostObj.none[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, true, undefined, false); }
function defineType(typeName, typeDefinition, hostObj) { if (typeName in typeToValueMapping) { throwError('Cannot define type \'' + typeName + '\' - type already defined'); } typeToValueMapping[typeName] = typeDefinition; if (typeof typeDefinition === 'number') { Object.defineProperty(hostObj, typeName.toUpperCase(), { value: typeToValueMapping[typeName], enumerable: true, writable: false, configurable: false }); } var typeMethodName = getTypeMethodName(typeName); var typeCheckFunction = function(item) { return isType(item, (typeToValueMapping[typeName] || typeName)); }; hostObj[typeMethodName] = typeCheckFunction; hostObj.not[typeMethodName] = function(value) { return !typeCheckFunction(value); }; hostObj.any[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, true, undefined, true); hostObj.all[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, undefined, true, false); hostObj.some[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, true, true, true); hostObj.none[typeMethodName] = getInterfaceFunction(typeCheckFunction, false, true, undefined, false); }
JavaScript
update(cache, { data: { addThought } }) { try { // read what is currently in the cache const { thoughts } = cache.readQuery({ query: QUERY_THOUGHTS }); // prepend the newest thought to the front of the array cache.writeQuery({ query: QUERY_THOUGHTS, data: { thoughts: [addThought, ...thoughts] }, }); } catch (e) { console.error(e); } // updates me cache const { me } = cache.readQuery({ query: QUERY_ME }); cache.writeQuery({ query: QUERY_ME, data: { me: { ...me, thoughts: [...me.thoughts, addThought] } }, }); }
update(cache, { data: { addThought } }) { try { // read what is currently in the cache const { thoughts } = cache.readQuery({ query: QUERY_THOUGHTS }); // prepend the newest thought to the front of the array cache.writeQuery({ query: QUERY_THOUGHTS, data: { thoughts: [addThought, ...thoughts] }, }); } catch (e) { console.error(e); } // updates me cache const { me } = cache.readQuery({ query: QUERY_ME }); cache.writeQuery({ query: QUERY_ME, data: { me: { ...me, thoughts: [...me.thoughts, addThought] } }, }); }
JavaScript
function compileCode(code, compilerConfig, onError) { try { var wrappedCode = startsWithJsx(code) ? wrapCodeInFragment(code) : code; var compiledCode = compile(wrappedCode, compilerConfig); return transpileImports(compiledCode); } catch (err) { if (onError) { onError(err); } } return ''; }
function compileCode(code, compilerConfig, onError) { try { var wrappedCode = startsWithJsx(code) ? wrapCodeInFragment(code) : code; var compiledCode = compile(wrappedCode, compilerConfig); return transpileImports(compiledCode); } catch (err) { if (onError) { onError(err); } } return ''; }
JavaScript
function Increment () { return ( <CounterContext.Consumer> {context => ( <button style={spanStyle} onClick={context.increment}>Increment</button> )} </CounterContext.Consumer> ); }
function Increment () { return ( <CounterContext.Consumer> {context => ( <button style={spanStyle} onClick={context.increment}>Increment</button> )} </CounterContext.Consumer> ); }
JavaScript
function flowTypeHandler(documentation, path) { const flowTypesPath = (0, _getFlowTypeFromReactComponent.default)(path); if (!flowTypesPath) { return; } (0, _getFlowTypeFromReactComponent.applyToFlowTypeProperties)(flowTypesPath, propertyPath => { setPropDescriptor(documentation, propertyPath); }); }
function flowTypeHandler(documentation, path) { const flowTypesPath = (0, _getFlowTypeFromReactComponent.default)(path); if (!flowTypesPath) { return; } (0, _getFlowTypeFromReactComponent.applyToFlowTypeProperties)(flowTypesPath, propertyPath => { setPropDescriptor(documentation, propertyPath); }); }
JavaScript
function filterSectionExamples(section, index) { return Object.assign({}, section, { content: [section.content[index]] }); }
function filterSectionExamples(section, index) { return Object.assign({}, section, { content: [section.content[index]] }); }
JavaScript
function _default(methodPath) { if (!types.MethodDefinition.check(methodPath.node) && !types.Property.check(methodPath.node)) { return false; } const name = (0, _getPropertyName.default)(methodPath); return componentMethods.indexOf(name) !== -1; }
function _default(methodPath) { if (!types.MethodDefinition.check(methodPath.node) && !types.Property.check(methodPath.node)) { return false; } const name = (0, _getPropertyName.default)(methodPath); return componentMethods.indexOf(name) !== -1; }
JavaScript
function parseExample(content, lang, modifiers, updateExample = x => x) { const example = { content, lang, settings: {} }; if (modifiers) { if (hasStringModifiers(modifiers)) { example.settings = modifiers.split(' ').reduce((obj, modifier) => { obj[modifier] = true; return obj; }, {}); } else { try { example.settings = JSON.parse(modifiers); } catch (err) { return { error: `Cannot parse modifiers for "${modifiers}". Use space-separated strings or JSON:\n\n${_consts.DOCS_DOCUMENTING}` }; } } } const updatedExample = updateExample(example); return Object.assign({}, updatedExample, { settings: (0, _lowercaseKeys.default)(updatedExample.settings) }); }
function parseExample(content, lang, modifiers, updateExample = x => x) { const example = { content, lang, settings: {} }; if (modifiers) { if (hasStringModifiers(modifiers)) { example.settings = modifiers.split(' ').reduce((obj, modifier) => { obj[modifier] = true; return obj; }, {}); } else { try { example.settings = JSON.parse(modifiers); } catch (err) { return { error: `Cannot parse modifiers for "${modifiers}". Use space-separated strings or JSON:\n\n${_consts.DOCS_DOCUMENTING}` }; } } } const updatedExample = updateExample(example); return Object.assign({}, updatedExample, { settings: (0, _lowercaseKeys.default)(updatedExample.settings) }); }
JavaScript
function Group(props) { var children = React.Children.toArray(props.children).filter(Boolean); if (children.length === 1) { return children; } // Insert separators var separator = props.separator; var separatorIsElement = React.isValidElement(separator); var items = [children.shift()]; children.forEach(function(item, index) { if (separatorIsElement) { var key = 'separator-' + (item.key || index); separator = React.cloneElement(separator, { key: key }); } items.push(separator, item); }); return items; }
function Group(props) { var children = React.Children.toArray(props.children).filter(Boolean); if (children.length === 1) { return children; } // Insert separators var separator = props.separator; var separatorIsElement = React.isValidElement(separator); var items = [children.shift()]; children.forEach(function(item, index) { if (separatorIsElement) { var key = 'separator-' + (item.key || index); separator = React.cloneElement(separator, { key: key }); } items.push(separator, item); }); return items; }
JavaScript
function findExportedComponentDefinitions(ast, recast) { const types = recast.types.namedTypes; const components = []; function exportDeclaration(path) { const definitions = (0, _resolveExportDeclaration.default)(path, types).reduce((acc, definition) => { if (isComponentDefinition(definition)) { acc.push(definition); } else { const resolved = (0, _resolveToValue.default)((0, _resolveHOC.default)(definition)); if (isComponentDefinition(resolved)) { acc.push(resolved); } } return acc; }, []).map(definition => resolveDefinition(definition, types)); if (definitions.length === 0) { return false; } definitions.forEach(definition => { if (definition && components.indexOf(definition) === -1) { components.push(definition); } }); return false; } recast.visit(ast, { visitFunctionDeclaration: ignore, visitFunctionExpression: ignore, visitClassDeclaration: ignore, visitClassExpression: ignore, visitIfStatement: ignore, visitWithStatement: ignore, visitSwitchStatement: ignore, visitCatchCause: ignore, visitWhileStatement: ignore, visitDoWhileStatement: ignore, visitForStatement: ignore, visitForInStatement: ignore, visitExportDeclaration: exportDeclaration, visitExportNamedDeclaration: exportDeclaration, visitExportDefaultDeclaration: exportDeclaration, visitAssignmentExpression: function visitAssignmentExpression(path) { // Ignore anything that is not `exports.X = ...;` or // `module.exports = ...;` if (!(0, _isExportsOrModuleAssignment.default)(path)) { return false; } // Resolve the value of the right hand side. It should resolve to a call // expression, something like React.createClass path = (0, _resolveToValue.default)(path.get('right')); if (!isComponentDefinition(path)) { path = (0, _resolveToValue.default)((0, _resolveHOC.default)(path)); if (!isComponentDefinition(path)) { return false; } } const definition = resolveDefinition(path, types); if (definition && components.indexOf(definition) === -1) { components.push(definition); } return false; } }); return components; }
function findExportedComponentDefinitions(ast, recast) { const types = recast.types.namedTypes; const components = []; function exportDeclaration(path) { const definitions = (0, _resolveExportDeclaration.default)(path, types).reduce((acc, definition) => { if (isComponentDefinition(definition)) { acc.push(definition); } else { const resolved = (0, _resolveToValue.default)((0, _resolveHOC.default)(definition)); if (isComponentDefinition(resolved)) { acc.push(resolved); } } return acc; }, []).map(definition => resolveDefinition(definition, types)); if (definitions.length === 0) { return false; } definitions.forEach(definition => { if (definition && components.indexOf(definition) === -1) { components.push(definition); } }); return false; } recast.visit(ast, { visitFunctionDeclaration: ignore, visitFunctionExpression: ignore, visitClassDeclaration: ignore, visitClassExpression: ignore, visitIfStatement: ignore, visitWithStatement: ignore, visitSwitchStatement: ignore, visitCatchCause: ignore, visitWhileStatement: ignore, visitDoWhileStatement: ignore, visitForStatement: ignore, visitForInStatement: ignore, visitExportDeclaration: exportDeclaration, visitExportNamedDeclaration: exportDeclaration, visitExportDefaultDeclaration: exportDeclaration, visitAssignmentExpression: function visitAssignmentExpression(path) { // Ignore anything that is not `exports.X = ...;` or // `module.exports = ...;` if (!(0, _isExportsOrModuleAssignment.default)(path)) { return false; } // Resolve the value of the right hand side. It should resolve to a call // expression, something like React.createClass path = (0, _resolveToValue.default)(path.get('right')); if (!isComponentDefinition(path)) { path = (0, _resolveToValue.default)((0, _resolveHOC.default)(path)); if (!isComponentDefinition(path)) { return false; } } const definition = resolveDefinition(path, types); if (definition && components.indexOf(definition) === -1) { components.push(definition); } return false; } }); return components; }
JavaScript
function transformAjvErrors() { var errors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; if (errors === null) { return []; } return errors.map(function (e) { var dataPath = e.dataPath, keyword = e.keyword, message = e.message, params = e.params, schemaPath = e.schemaPath; var property = "".concat(dataPath); // put data in expected format return { name: keyword, property: property, message: message, params: params, // specific to ajv stack: "".concat(property, " ").concat(message).trim(), schemaPath: schemaPath }; }); }
function transformAjvErrors() { var errors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; if (errors === null) { return []; } return errors.map(function (e) { var dataPath = e.dataPath, keyword = e.keyword, message = e.message, params = e.params, schemaPath = e.schemaPath; var property = "".concat(dataPath); // put data in expected format return { name: keyword, property: property, message: message, params: params, // specific to ajv stack: "".concat(property, " ").concat(message).trim(), schemaPath: schemaPath }; }); }
JavaScript
function validateFormData(formData, schema, customValidate, transformErrors) { var additionalMetaSchemas = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var customFormats = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; // Include form data with undefined values, which is required for validation. var definitions = schema.definitions; formData = (0, _utils.getDefaultFormState)(schema, formData, definitions, true); var newMetaSchemas = !(0, _utils.deepEquals)(formerMetaSchema, additionalMetaSchemas); var newFormats = !(0, _utils.deepEquals)(formerCustomFormats, customFormats); if (newMetaSchemas || newFormats) { ajv = createAjvInstance(); } // add more schemas to validate against if (additionalMetaSchemas && newMetaSchemas && (0, _isArray["default"])(additionalMetaSchemas)) { ajv.addMetaSchema(additionalMetaSchemas); formerMetaSchema = additionalMetaSchemas; } // add more custom formats to validate against if (customFormats && newFormats && (0, _utils.isObject)(customFormats)) { (0, _keys["default"])(customFormats).forEach(function (formatName) { ajv.addFormat(formatName, customFormats[formatName]); }); formerCustomFormats = customFormats; } var validationError = null; try { ajv.validate(schema, formData); } catch (err) { validationError = err; } var errors = transformAjvErrors(ajv.errors); // Clear errors to prevent persistent errors, see #1104 ajv.errors = null; var noProperMetaSchema = validationError && validationError.message && typeof validationError.message === "string" && validationError.message.includes("no schema with key or ref "); if (noProperMetaSchema) { errors = [].concat((0, _toConsumableArray2["default"])(errors), [{ stack: validationError.message }]); } if (typeof transformErrors === "function") { errors = transformErrors(errors); } var errorSchema = toErrorSchema(errors); if (noProperMetaSchema) { errorSchema = (0, _objectSpread6["default"])({}, errorSchema, { $schema: { __errors: [validationError.message] } }); } if (typeof customValidate !== "function") { return { errors: errors, errorSchema: errorSchema }; } var errorHandler = customValidate(formData, createErrorHandler(formData)); var userErrorSchema = unwrapErrorHandler(errorHandler); var newErrorSchema = (0, _utils.mergeObjects)(errorSchema, userErrorSchema, true); // XXX: The errors list produced is not fully compliant with the format // exposed by the jsonschema lib, which contains full field paths and other // properties. var newErrors = toErrorList(newErrorSchema); return { errors: newErrors, errorSchema: newErrorSchema }; }
function validateFormData(formData, schema, customValidate, transformErrors) { var additionalMetaSchemas = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var customFormats = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; // Include form data with undefined values, which is required for validation. var definitions = schema.definitions; formData = (0, _utils.getDefaultFormState)(schema, formData, definitions, true); var newMetaSchemas = !(0, _utils.deepEquals)(formerMetaSchema, additionalMetaSchemas); var newFormats = !(0, _utils.deepEquals)(formerCustomFormats, customFormats); if (newMetaSchemas || newFormats) { ajv = createAjvInstance(); } // add more schemas to validate against if (additionalMetaSchemas && newMetaSchemas && (0, _isArray["default"])(additionalMetaSchemas)) { ajv.addMetaSchema(additionalMetaSchemas); formerMetaSchema = additionalMetaSchemas; } // add more custom formats to validate against if (customFormats && newFormats && (0, _utils.isObject)(customFormats)) { (0, _keys["default"])(customFormats).forEach(function (formatName) { ajv.addFormat(formatName, customFormats[formatName]); }); formerCustomFormats = customFormats; } var validationError = null; try { ajv.validate(schema, formData); } catch (err) { validationError = err; } var errors = transformAjvErrors(ajv.errors); // Clear errors to prevent persistent errors, see #1104 ajv.errors = null; var noProperMetaSchema = validationError && validationError.message && typeof validationError.message === "string" && validationError.message.includes("no schema with key or ref "); if (noProperMetaSchema) { errors = [].concat((0, _toConsumableArray2["default"])(errors), [{ stack: validationError.message }]); } if (typeof transformErrors === "function") { errors = transformErrors(errors); } var errorSchema = toErrorSchema(errors); if (noProperMetaSchema) { errorSchema = (0, _objectSpread6["default"])({}, errorSchema, { $schema: { __errors: [validationError.message] } }); } if (typeof customValidate !== "function") { return { errors: errors, errorSchema: errorSchema }; } var errorHandler = customValidate(formData, createErrorHandler(formData)); var userErrorSchema = unwrapErrorHandler(errorHandler); var newErrorSchema = (0, _utils.mergeObjects)(errorSchema, userErrorSchema, true); // XXX: The errors list produced is not fully compliant with the format // exposed by the jsonschema lib, which contains full field paths and other // properties. var newErrors = toErrorList(newErrorSchema); return { errors: newErrors, errorSchema: newErrorSchema }; }
JavaScript
function transpileImports(code) { // Don't do anything when the code has nothing that looks like an import if (!hasImports(code)) { return code; } // Ignore errors, they should be caught by Buble var ast = getAst(code); if (!ast) { return code; } var offset = 0; walk(ast, { // import foo from 'foo' // import 'foo' enter: function enter(node) { if (node.type === 'ImportDeclaration' && node.source) { var start = node.start + offset; var end = node.end + offset; var statement = code.substring(start, end); var transpiledStatement = rewriteImports(statement); code = code.substring(0, start) + transpiledStatement + code.substring(end); offset += transpiledStatement.length - statement.length; } } }); return code; }
function transpileImports(code) { // Don't do anything when the code has nothing that looks like an import if (!hasImports(code)) { return code; } // Ignore errors, they should be caught by Buble var ast = getAst(code); if (!ast) { return code; } var offset = 0; walk(ast, { // import foo from 'foo' // import 'foo' enter: function enter(node) { if (node.type === 'ImportDeclaration' && node.source) { var start = node.start + offset; var end = node.end + offset; var statement = code.substring(start, end); var transpiledStatement = rewriteImports(statement); code = code.substring(0, start) + transpiledStatement + code.substring(end); offset += transpiledStatement.length - statement.length; } } }); return code; }
JavaScript
function chunkify(markdown, updateExample, playgroundLangs = PLAYGROUND_LANGS) { const codeChunks = []; /* * - Highlight code in fenced code blocks with defined language (```html). * - Extract indented and fenced code blocks with lang javascript|js|jsx or if lang is not defined. * - Leave all other Markdown or HTML as is. */ function processCode() { return ast => { (0, _unistUtilVisit.default)(ast, 'code', node => { const example = (0, _parseExample.default)(node.value, node.lang, node.meta, updateExample); if (example.error) { node.lang = undefined; node.value = example.error; return; } const lang = example.lang; node.lang = lang; if (!lang || playgroundLangs.indexOf(lang) !== -1 && !example.settings.static) { codeChunks.push({ type: 'code', content: example.content, settings: example.settings }); node.type = 'html'; node.value = CODE_PLACEHOLDER; } else { node.meta = null; node.value = (0, _highlightCode.default)(example.content, lang); } }); }; } const rendered = (0, _remark.default)().use(processCode).processSync(markdown).toString(); const chunks = []; const textChunks = rendered.split(CODE_PLACEHOLDER); textChunks.forEach(chunk => { chunk = chunk.trim(); if (chunk) { chunks.push({ type: 'markdown', content: chunk }); } const code = codeChunks.shift(); if (code) { chunks.push(code); } }); return chunks; }
function chunkify(markdown, updateExample, playgroundLangs = PLAYGROUND_LANGS) { const codeChunks = []; /* * - Highlight code in fenced code blocks with defined language (```html). * - Extract indented and fenced code blocks with lang javascript|js|jsx or if lang is not defined. * - Leave all other Markdown or HTML as is. */ function processCode() { return ast => { (0, _unistUtilVisit.default)(ast, 'code', node => { const example = (0, _parseExample.default)(node.value, node.lang, node.meta, updateExample); if (example.error) { node.lang = undefined; node.value = example.error; return; } const lang = example.lang; node.lang = lang; if (!lang || playgroundLangs.indexOf(lang) !== -1 && !example.settings.static) { codeChunks.push({ type: 'code', content: example.content, settings: example.settings }); node.type = 'html'; node.value = CODE_PLACEHOLDER; } else { node.meta = null; node.value = (0, _highlightCode.default)(example.content, lang); } }); }; } const rendered = (0, _remark.default)().use(processCode).processSync(markdown).toString(); const chunks = []; const textChunks = rendered.split(CODE_PLACEHOLDER); textChunks.forEach(chunk => { chunk = chunk.trim(); if (chunk) { chunks.push({ type: 'markdown', content: chunk }); } const code = codeChunks.shift(); if (code) { chunks.push(code); } }); return chunks; }
JavaScript
function processCode() { return ast => { (0, _unistUtilVisit.default)(ast, 'code', node => { const example = (0, _parseExample.default)(node.value, node.lang, node.meta, updateExample); if (example.error) { node.lang = undefined; node.value = example.error; return; } const lang = example.lang; node.lang = lang; if (!lang || playgroundLangs.indexOf(lang) !== -1 && !example.settings.static) { codeChunks.push({ type: 'code', content: example.content, settings: example.settings }); node.type = 'html'; node.value = CODE_PLACEHOLDER; } else { node.meta = null; node.value = (0, _highlightCode.default)(example.content, lang); } }); }; }
function processCode() { return ast => { (0, _unistUtilVisit.default)(ast, 'code', node => { const example = (0, _parseExample.default)(node.value, node.lang, node.meta, updateExample); if (example.error) { node.lang = undefined; node.value = example.error; return; } const lang = example.lang; node.lang = lang; if (!lang || playgroundLangs.indexOf(lang) !== -1 && !example.settings.static) { codeChunks.push({ type: 'code', content: example.content, settings: example.settings }); node.type = 'html'; node.value = CODE_PLACEHOLDER; } else { node.meta = null; node.value = (0, _highlightCode.default)(example.content, lang); } }); }; }
JavaScript
function commonDir (files) { return files .map(path.dirname) .map(function (dir) { return dir.split(path.sep) }) .reduce(commonSequence) .concat(['']) .join(path.sep) }
function commonDir (files) { return files .map(path.dirname) .map(function (dir) { return dir.split(path.sep) }) .reduce(commonSequence) .concat(['']) .join(path.sep) }
JavaScript
function loopElements(loop) { if(loop == 1) { let colorClick = document.querySelectorAll('.colorBtn'); for(var i = 0; i < colorClick.length; i++) { colorClick[i].addEventListener('click', colorDisplay); } } else if(loop == 2) { let iconClick = document.querySelectorAll('.icons'); for(var i = 0; i < iconClick.length; i++) { iconClick[i].addEventListener('click', iconDisplay); } } }
function loopElements(loop) { if(loop == 1) { let colorClick = document.querySelectorAll('.colorBtn'); for(var i = 0; i < colorClick.length; i++) { colorClick[i].addEventListener('click', colorDisplay); } } else if(loop == 2) { let iconClick = document.querySelectorAll('.icons'); for(var i = 0; i < iconClick.length; i++) { iconClick[i].addEventListener('click', iconDisplay); } } }
JavaScript
function colorDisplay() { let fillColor = document.getElementById('dropColor'); fillColor.style.backgroundColor = habitColors[this.id]; //fillColor.style.border = "5px solid" + habitColors[this.id]; showDropdown(1, 'dropdownContent showing'); }
function colorDisplay() { let fillColor = document.getElementById('dropColor'); fillColor.style.backgroundColor = habitColors[this.id]; //fillColor.style.border = "5px solid" + habitColors[this.id]; showDropdown(1, 'dropdownContent showing'); }
JavaScript
function iconDisplay() { let startText = document.getElementById('downTextIcon'); startText.innerHTML = iconArr[this.id]; showDropdown(2, 'dropdownContent showing'); }
function iconDisplay() { let startText = document.getElementById('downTextIcon'); startText.innerHTML = iconArr[this.id]; showDropdown(2, 'dropdownContent showing'); }
JavaScript
function calendarIconButtons() { let calendarIconBtn = document.querySelectorAll(".calendar-icon-container") for (let i = 0; i < calendarIconBtn.length; i++){ calendarIconBtn[i].addEventListener ("click", function(event){ modal.style.display = "block"; let modalTitle = document.getElementById("modal-title"); modalTitle.innerHTML = "Change habit" removeBtn.classList.remove("hideBtn") updateBtn.classList.remove("hideBtn") addHabitBtn.classList.add("hideBtn") let habitData = getHabit(this.id); //send calendarIconBtn's ID the the function in dao to retrieve data document.getElementById("createHabitName").value = habitData.name; document.getElementById("createHabitDescription").value = habitData.description; document.getElementById("downTextIcon").innerHTML = habitData.icon; document.getElementById("dropColor").style.backgroundColor = habitData.color; }, false); } }
function calendarIconButtons() { let calendarIconBtn = document.querySelectorAll(".calendar-icon-container") for (let i = 0; i < calendarIconBtn.length; i++){ calendarIconBtn[i].addEventListener ("click", function(event){ modal.style.display = "block"; let modalTitle = document.getElementById("modal-title"); modalTitle.innerHTML = "Change habit" removeBtn.classList.remove("hideBtn") updateBtn.classList.remove("hideBtn") addHabitBtn.classList.add("hideBtn") let habitData = getHabit(this.id); //send calendarIconBtn's ID the the function in dao to retrieve data document.getElementById("createHabitName").value = habitData.name; document.getElementById("createHabitDescription").value = habitData.description; document.getElementById("downTextIcon").innerHTML = habitData.icon; document.getElementById("dropColor").style.backgroundColor = habitData.color; }, false); } }
JavaScript
function clearInputFields() { console.log() document.getElementById("createHabitName").value = ""; document.getElementById("createHabitDescription").value = "" document.getElementById("downTextIcon").innerHTML = "Pick an Icon"; document.getElementById("dropColor").style.backgroundColor = ""; let modalTitle = document.getElementById("modal-title"); modalTitle.innerHTML = "Add habit"; removeBtn.classList.add("hideBtn"); updateBtn.classList.add("hideBtn") addHabitBtn.classList.remove("hideBtn") }
function clearInputFields() { console.log() document.getElementById("createHabitName").value = ""; document.getElementById("createHabitDescription").value = "" document.getElementById("downTextIcon").innerHTML = "Pick an Icon"; document.getElementById("dropColor").style.backgroundColor = ""; let modalTitle = document.getElementById("modal-title"); modalTitle.innerHTML = "Add habit"; removeBtn.classList.add("hideBtn"); updateBtn.classList.add("hideBtn") addHabitBtn.classList.remove("hideBtn") }
JavaScript
function parseJSON(response) { if (response.status === 204 || response.status === 205) { return null; } return response.json(); //return response; }
function parseJSON(response) { if (response.status === 204 || response.status === 205) { return null; } return response.json(); //return response; }
JavaScript
function orderResultsByIdForFindById(results, callback){ // a findById query can look something like: // {"where":{"and":[{"id":{"inq":["4","2","3","1"]}},{"vip":true}]}} var findByIdsWithSearch = conditions.where && conditions.where.and && conditions.where.and[0] && conditions.where.and[0].id && conditions.where.and[0].id.inq; // a findById query can also look something like: // {"where":{"id":{"inq":["4","2","3","1"]}}} var findByIdsWithoutSearch = conditions.where && conditions.where.id && conditions.where.id.inq; var findByIds = findByIdsWithSearch || findByIdsWithoutSearch; // if it doesn't seem to be findById we don't have to hold // loopback's hand if (!findByIds) return callback(null, results); var resultsById = _.keyBy(results, "id"); callback(null, _.map(findByIds, function (i){ return resultsById[i]; })); }
function orderResultsByIdForFindById(results, callback){ // a findById query can look something like: // {"where":{"and":[{"id":{"inq":["4","2","3","1"]}},{"vip":true}]}} var findByIdsWithSearch = conditions.where && conditions.where.and && conditions.where.and[0] && conditions.where.and[0].id && conditions.where.and[0].id.inq; // a findById query can also look something like: // {"where":{"id":{"inq":["4","2","3","1"]}}} var findByIdsWithoutSearch = conditions.where && conditions.where.id && conditions.where.id.inq; var findByIds = findByIdsWithSearch || findByIdsWithoutSearch; // if it doesn't seem to be findById we don't have to hold // loopback's hand if (!findByIds) return callback(null, results); var resultsById = _.keyBy(results, "id"); callback(null, _.map(findByIds, function (i){ return resultsById[i]; })); }
JavaScript
function componentizeNotQuery(notQueries) { var componentizedNot = []; if (notQueries.constructor !== Array) { for (var propertyName in notQueries) { componentizedNot.push(componentizeFacet(propertyName, notQueries[propertyName])) } } else { notQueries.forEach(function (element, index) { for (var propertyName in element) { componentizedNot.push(componentizeFacet(propertyName, element[propertyName])) } }); } return componentizedNot; }
function componentizeNotQuery(notQueries) { var componentizedNot = []; if (notQueries.constructor !== Array) { for (var propertyName in notQueries) { componentizedNot.push(componentizeFacet(propertyName, notQueries[propertyName])) } } else { notQueries.forEach(function (element, index) { for (var propertyName in element) { componentizedNot.push(componentizeFacet(propertyName, element[propertyName])) } }); } return componentizedNot; }
JavaScript
function fetchKeysForBatch(){ riak.search(bucketName, extend({ size: batchSize, from: batch * batchSize }, conditions), function(error, ids){ if (error) return apiCallback(error); // hope you can fit your keys in memory. YOLO. some day maybe // we'll make this do operations in batches rather than load // the whole key set ;) keys.push.apply(keys, ids); if (ids.length < batchSize) return apiCallback(null, keys); batch++; fetchKeysForBatch(); }); }
function fetchKeysForBatch(){ riak.search(bucketName, extend({ size: batchSize, from: batch * batchSize }, conditions), function(error, ids){ if (error) return apiCallback(error); // hope you can fit your keys in memory. YOLO. some day maybe // we'll make this do operations in batches rather than load // the whole key set ;) keys.push.apply(keys, ids); if (ids.length < batchSize) return apiCallback(null, keys); batch++; fetchKeysForBatch(); }); }
JavaScript
function mapOptions(optionNames) { var config = {}, // New config object // Comma separated string to Array names = optionNames.split(/\s*\,\s*/), // Turn arguments into array, starting at index 1 args = [].slice.call(arguments, 1), isHash; names.forEach(function (optionName) { // Use first argument as params object... if (args[0] && args[0][optionName]) { config[optionName] = args[0][optionName]; isHash = true; } }); // Or, grab the options from the arguments if (!isHash) { names.forEach(function (optionName, index) { config[optionName] = args[index]; }); } return config; }
function mapOptions(optionNames) { var config = {}, // New config object // Comma separated string to Array names = optionNames.split(/\s*\,\s*/), // Turn arguments into array, starting at index 1 args = [].slice.call(arguments, 1), isHash; names.forEach(function (optionName) { // Use first argument as params object... if (args[0] && args[0][optionName]) { config[optionName] = args[0][optionName]; isHash = true; } }); // Or, grab the options from the arguments if (!isHash) { names.forEach(function (optionName, index) { config[optionName] = args[index]; }); } return config; }
JavaScript
function factory(sharedProperties, defaultProperties, instanceInit, factoryInit, ignoreOptions) { var optionNames = 'sharedProperties, defaultProperties,' + ' instanceInit, factoryInit, ignoreOptions', config, initObj = o(); config = mapOptions(optionNames, sharedProperties, defaultProperties, instanceInit, factoryInit, ignoreOptions); config.instanceInit = config.instanceInit || defaultInit; // factoryInit can be used to initialize shared private state. if (typeof config.factoryInit === 'function') { config.factoryInit.call(initObj); } return bless(function (options) { var defaultProperties = copy(config.defaultProperties || {}, sharedProperties = extend(config.sharedProperties || {}, initObj)), instance = (config.ignoreOptions) ? defaultProperties : extend({}, defaultProperties, options), obj, init; obj = extend(o(sharedProperties, instance)); init = config.instanceInit; return ((typeof init === 'function') ? init.call(obj, options) : obj); }); }
function factory(sharedProperties, defaultProperties, instanceInit, factoryInit, ignoreOptions) { var optionNames = 'sharedProperties, defaultProperties,' + ' instanceInit, factoryInit, ignoreOptions', config, initObj = o(); config = mapOptions(optionNames, sharedProperties, defaultProperties, instanceInit, factoryInit, ignoreOptions); config.instanceInit = config.instanceInit || defaultInit; // factoryInit can be used to initialize shared private state. if (typeof config.factoryInit === 'function') { config.factoryInit.call(initObj); } return bless(function (options) { var defaultProperties = copy(config.defaultProperties || {}, sharedProperties = extend(config.sharedProperties || {}, initObj)), instance = (config.ignoreOptions) ? defaultProperties : extend({}, defaultProperties, options), obj, init; obj = extend(o(sharedProperties, instance)); init = config.instanceInit; return ((typeof init === 'function') ? init.call(obj, options) : obj); }); }
JavaScript
function rdelete(m, key) { if (m.parent && m.parent.filename === require.resolve(key)) { delete m.parent; } for (var i = m.children.length - 1; i >= 0; i--) { if (m.children[i].filename === require.resolve(key)) { m.children.splice(i, 1); } else { rdelete(m.children[i], key); } } }
function rdelete(m, key) { if (m.parent && m.parent.filename === require.resolve(key)) { delete m.parent; } for (var i = m.children.length - 1; i >= 0; i--) { if (m.children[i].filename === require.resolve(key)) { m.children.splice(i, 1); } else { rdelete(m.children[i], key); } } }
JavaScript
function rdelete(m, key) { if (m.parent && m.parent.filename === require.resolve(key)) { delete m.parent; } for (let i = m.children.length - 1; i >= 0; i--) { if (m.children[i].filename === require.resolve(key)) { m.children.splice(i, 1); } else { rdelete(m.children[i], key); } } }
function rdelete(m, key) { if (m.parent && m.parent.filename === require.resolve(key)) { delete m.parent; } for (let i = m.children.length - 1; i >= 0; i--) { if (m.children[i].filename === require.resolve(key)) { m.children.splice(i, 1); } else { rdelete(m.children[i], key); } } }
JavaScript
open(ip, password) { this.ip = ip this.password = password this.ws = new WebSocketAdapter(`ws://${ip}:8266`) this.ws.on('open', () => { this.ws.on('message', this._handleMessage.bind(this)) }) this.ws.on('close', () => { this.emit('disconnected') }) }
open(ip, password) { this.ip = ip this.password = password this.ws = new WebSocketAdapter(`ws://${ip}:8266`) this.ws.on('open', () => { this.ws.on('message', this._handleMessage.bind(this)) }) this.ws.on('close', () => { this.emit('disconnected') }) }
JavaScript
execute(code) { let interval = 30 let page = 80 let enterRawRepl = () => { return new Promise((resolve) => { this._enterRawRepl() setTimeout(() => { resolve() }, interval*2) }) } let executeRaw = () => { return new Promise((resolve, reject) => { let lines = code.split('\n') let t = 0 this.emit('output', `\r\n`) for(let i = 0; i < lines.length; i++) { let line = lines[i] if (line.length < page) { t += lines[i].length setTimeout(() => { this.evaluate(line+'\n') this.emit('output', `.`) }, t) } else { for(let j = 0; j < Math.ceil(line.length / page); j++) { t += page setTimeout(() => { this.evaluate(line.substr(j*1024, 1024)) this.emit('output', `.`) }, t) } } } setTimeout(() => { resolve() }, t+100) }) } let exitRawRepl = () => { this._exitRawRepl() return Promise.resolve() } return enterRawRepl() .then(executeRaw) .then(exitRawRepl) }
execute(code) { let interval = 30 let page = 80 let enterRawRepl = () => { return new Promise((resolve) => { this._enterRawRepl() setTimeout(() => { resolve() }, interval*2) }) } let executeRaw = () => { return new Promise((resolve, reject) => { let lines = code.split('\n') let t = 0 this.emit('output', `\r\n`) for(let i = 0; i < lines.length; i++) { let line = lines[i] if (line.length < page) { t += lines[i].length setTimeout(() => { this.evaluate(line+'\n') this.emit('output', `.`) }, t) } else { for(let j = 0; j < Math.ceil(line.length / page); j++) { t += page setTimeout(() => { this.evaluate(line.substr(j*1024, 1024)) this.emit('output', `.`) }, t) } } } setTimeout(() => { resolve() }, t+100) }) } let exitRawRepl = () => { this._exitRawRepl() return Promise.resolve() } return enterRawRepl() .then(executeRaw) .then(exitRawRepl) }
JavaScript
listFiles() { const code = `print(' ') from os import listdir print(listdir()) ` this.execute(code) }
listFiles() { const code = `print(' ') from os import listdir print(listdir()) ` this.execute(code) }