language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function wrap(impl) { if (impl === null) return null; assert(isNative(impl)); var wrapper = impl.__wrapper8e3dd93a60__; if (wrapper != null) { return wrapper; } return impl.__wrapper8e3dd93a60__ = new (getWrapperConstructor(impl, impl))(impl); }
function wrap(impl) { if (impl === null) return null; assert(isNative(impl)); var wrapper = impl.__wrapper8e3dd93a60__; if (wrapper != null) { return wrapper; } return impl.__wrapper8e3dd93a60__ = new (getWrapperConstructor(impl, impl))(impl); }
JavaScript
function processStateData(data) { // We found a redirect and need to handle it instead of the current state... if (data) { if (handleRedirect(data)) { return null; } if (data.status) { switch (data.status) { case 200: case 201: case 204: // Intentional fall-through for all expected 2xx states _currentState++; if (data.results) { cache.update({ id: "main", data: data.results }); if (data.results && data.results._links && data.results._links.applications) { _currentState = 3; } } break; case 401: // 401 means it's time to supply credentials data.Link = checkForResponseHeaderUrl(data.headers); // Track how many failed authorize attempts occur if (_currentState === 1) { _authErrorCounter++; } else { _currentState++; } break; case 400: case 404: // Reset for either 400 or 404 resetState(); return false; default: // Other errors if (_authErrorCounter > 6) { resetState(); return false; } _authErrorCounter++; break; } } return true; } resetState(); return false; }
function processStateData(data) { // We found a redirect and need to handle it instead of the current state... if (data) { if (handleRedirect(data)) { return null; } if (data.status) { switch (data.status) { case 200: case 201: case 204: // Intentional fall-through for all expected 2xx states _currentState++; if (data.results) { cache.update({ id: "main", data: data.results }); if (data.results && data.results._links && data.results._links.applications) { _currentState = 3; } } break; case 401: // 401 means it's time to supply credentials data.Link = checkForResponseHeaderUrl(data.headers); // Track how many failed authorize attempts occur if (_currentState === 1) { _authErrorCounter++; } else { _currentState++; } break; case 400: case 404: // Reset for either 400 or 404 resetState(); return false; default: // Other errors if (_authErrorCounter > 6) { resetState(); return false; } _authErrorCounter++; break; } } return true; } resetState(); return false; }
JavaScript
function handleRedirect(data) { var link = "", result = false; if (data && data._links && data._links.redirect) { link = data._links.redirect; } if (link) { transport.clientRequest({ url: link, type: "get", callback: handleState }); result = true; } return result; }
function handleRedirect(data) { var link = "", result = false; if (data && data._links && data._links.redirect) { link = data._links.redirect; } if (link) { transport.clientRequest({ url: link, type: "get", callback: handleState }); result = true; } return result; }
JavaScript
function checkForResponseHeaderUrl(headers) { var url = undefined, obj = _generalHelper.parseHeaders(headers); if (obj["WWW-Authenticate"] && obj["WWW-Authenticate"].MsRtcOAuth) { url = obj["WWW-Authenticate"].MsRtcOAuth.href; } return url; }
function checkForResponseHeaderUrl(headers) { var url = undefined, obj = _generalHelper.parseHeaders(headers); if (obj["WWW-Authenticate"] && obj["WWW-Authenticate"].MsRtcOAuth) { url = obj["WWW-Authenticate"].MsRtcOAuth.href; } return url; }
JavaScript
function XMessage(message) { var xTitle = $('<div>').addClass('sender'); var xStatus = $('<div>').addClass('status'); var xText = $('<div>').addClass('text').text(message.text()); var xMessage = $('<div>').addClass('message'); xMessage.append(xTitle, xStatus, xText); if (message.sender) { message.sender.displayName.get().then(function(displayName) { xTitle.text(displayName); }); if (message.sender.displayName()) { xTitle.text(message.sender.displayName()); } } message.status.changed(function(status) { //xStatus.text(status); }); if (message.sender.id() == client.personsAndGroupsManager.mePerson.id()) xMessage.addClass("fromMe"); return xMessage; }
function XMessage(message) { var xTitle = $('<div>').addClass('sender'); var xStatus = $('<div>').addClass('status'); var xText = $('<div>').addClass('text').text(message.text()); var xMessage = $('<div>').addClass('message'); xMessage.append(xTitle, xStatus, xText); if (message.sender) { message.sender.displayName.get().then(function(displayName) { xTitle.text(displayName); }); if (message.sender.displayName()) { xTitle.text(message.sender.displayName()); } } message.status.changed(function(status) { //xStatus.text(status); }); if (message.sender.id() == client.personsAndGroupsManager.mePerson.id()) xMessage.addClass("fromMe"); return xMessage; }
JavaScript
function sendNotification() { var msg = $('#inputmsg').val(); var sip = $('#sendto').val(); var serviceUrl = window.skypeWebApp.serviceUrl + '/SimpleNotifyJob'; if ((sip == "") || (msg == "") || sip.indexOf('@') < 0 || sip.indexOf('sip:') < 0) { alert('Please input valid sip Uri or message'); return; } var notifydata = { TargetUri: sip, NotificationMessage: msg } $('#status').html('sending..'); ajaxrequest('Post', serviceUrl, notifydata, 'text').done(function (data) { $('#status').html("Send out message successfully, agent will get message very soon."); //clearTimeout(timeout); }); function myFunction() { $('#status').html('Send out message time out, try it again?'); } }
function sendNotification() { var msg = $('#inputmsg').val(); var sip = $('#sendto').val(); var serviceUrl = window.skypeWebApp.serviceUrl + '/SimpleNotifyJob'; if ((sip == "") || (msg == "") || sip.indexOf('@') < 0 || sip.indexOf('sip:') < 0) { alert('Please input valid sip Uri or message'); return; } var notifydata = { TargetUri: sip, NotificationMessage: msg } $('#status').html('sending..'); ajaxrequest('Post', serviceUrl, notifydata, 'text').done(function (data) { $('#status').html("Send out message successfully, agent will get message very soon."); //clearTimeout(timeout); }); function myFunction() { $('#status').html('Send out message time out, try it again?'); } }
JavaScript
function GetAdhocMeeting() { $(".modal").show(); var getadhocmeetinginput = { Subject: 'adhocMeeting', Description: 'adhocMeeting', AccessLevel: '' }; ajaxrequest('post', window.skypeWebApp.serviceUrl + '/GetAdhocMeetingJob',getadhocmeetinginput,'text').done(function (d) { var data = JSON.parse(d); var meetingUrl = data.JoinUrl; var discoverUri = data.DiscoverUri; var onlineMeetingUri = data.OnlineMeetingUri; if (meetingUrl || discoverUri) { $('#txt-meetingurl').val(meetingUrl); $('#meetingUrl').text('meetingUrl: ' + meetingUrl); $('#discoverUri').text('discoverUri: ' + discoverUri); $('#onlineMeetingUri').text('onlineMeetingUri: ' + onlineMeetingUri); $('#adhocmeetingresources').show(); } window.scrollTo(0, document.body.scrollHeight); }) .fail( function () { alert('Get adhoc meeting failed, please try again.'); } ) .always( function () { $(".modal").hide(); }); }
function GetAdhocMeeting() { $(".modal").show(); var getadhocmeetinginput = { Subject: 'adhocMeeting', Description: 'adhocMeeting', AccessLevel: '' }; ajaxrequest('post', window.skypeWebApp.serviceUrl + '/GetAdhocMeetingJob',getadhocmeetinginput,'text').done(function (d) { var data = JSON.parse(d); var meetingUrl = data.JoinUrl; var discoverUri = data.DiscoverUri; var onlineMeetingUri = data.OnlineMeetingUri; if (meetingUrl || discoverUri) { $('#txt-meetingurl').val(meetingUrl); $('#meetingUrl').text('meetingUrl: ' + meetingUrl); $('#discoverUri').text('discoverUri: ' + discoverUri); $('#onlineMeetingUri').text('onlineMeetingUri: ' + onlineMeetingUri); $('#adhocmeetingresources').show(); } window.scrollTo(0, document.body.scrollHeight); }) .fail( function () { alert('Get adhoc meeting failed, please try again.'); } ) .always( function () { $(".modal").hide(); }); }
JavaScript
function deletethenstartnew() { ajaxrequest('delete', window.skypeWebApp.serviceUrl + '/ListeningJob').done(function (data) { console.log('deleted job'); }) .always( function () { StartMessageInvitationHandler(); } ); }
function deletethenstartnew() { ajaxrequest('delete', window.skypeWebApp.serviceUrl + '/ListeningJob').done(function (data) { console.log('deleted job'); }) .always( function () { StartMessageInvitationHandler(); } ); }
JavaScript
function processHeader(header) { var data = $.trim(header).split("\n"); for (var line in data) { if (data[line].indexOf("boundary") !== -1) { var temp = data[line].split(";"); for (var item in temp) { if (temp[item].indexOf("boundary") !== -1) { var result = $.trim(temp[item].split("=")[1]); if (result[0] === '"' && result[result.length - 1] === '"') { return result.slice(1, -1); } return result; } } } } // No boundary was found in the results... return defaultBoundary; }
function processHeader(header) { var data = $.trim(header).split("\n"); for (var line in data) { if (data[line].indexOf("boundary") !== -1) { var temp = data[line].split(";"); for (var item in temp) { if (temp[item].indexOf("boundary") !== -1) { var result = $.trim(temp[item].split("=")[1]); if (result[0] === '"' && result[result.length - 1] === '"') { return result.slice(1, -1); } return result; } } } } // No boundary was found in the results... return defaultBoundary; }
JavaScript
function processBody(boundary, body) { var data = body.split("--" + boundary), parsed = [], messages = []; for (var part in data) { if ($.trim(data[part]) !== "" && $.trim(data[part]) !== "--") { var partData = $.trim(data[part]).split("\r\n"), message = { status: null, statusText: null, responseText: "", header: "", messageId: null }, contentType = null; for (var item in partData) { if (contentType === null && partData[item].indexOf("Content-Type") !== -1) { contentType = determineContentType(partData[item]); if (contentType !== null && message.header === "") { message.header = readHeader(partData, item); } } else if (partData[item].indexOf("HTTP/1.1") !== -1) { message.status = partData[item].split(" ")[1]; message.header = readHeader(partData, ++item); } else if (contentType !== null && $.trim(partData[item]) !== "") { message.responseText = partData[item]; if (contentType === "json") { message.results = JSON.parse($.trim(partData[item])); } } } messages.push(message); } } return messages; }
function processBody(boundary, body) { var data = body.split("--" + boundary), parsed = [], messages = []; for (var part in data) { if ($.trim(data[part]) !== "" && $.trim(data[part]) !== "--") { var partData = $.trim(data[part]).split("\r\n"), message = { status: null, statusText: null, responseText: "", header: "", messageId: null }, contentType = null; for (var item in partData) { if (contentType === null && partData[item].indexOf("Content-Type") !== -1) { contentType = determineContentType(partData[item]); if (contentType !== null && message.header === "") { message.header = readHeader(partData, item); } } else if (partData[item].indexOf("HTTP/1.1") !== -1) { message.status = partData[item].split(" ")[1]; message.header = readHeader(partData, ++item); } else if (contentType !== null && $.trim(partData[item]) !== "") { message.responseText = partData[item]; if (contentType === "json") { message.results = JSON.parse($.trim(partData[item])); } } } messages.push(message); } } return messages; }
JavaScript
function determineContentType(data) { var contentType = null, expectedType = "json"; if (data.indexOf("http; msgtype=response") === -1) { var index = data.indexOf(expectedType); if (index !== -1) { contentType = expectedType; } else { contentType = $.trim(data).split('/')[1]; } } return contentType; }
function determineContentType(data) { var contentType = null, expectedType = "json"; if (data.indexOf("http; msgtype=response") === -1) { var index = data.indexOf(expectedType); if (index !== -1) { contentType = expectedType; } else { contentType = $.trim(data).split('/')[1]; } } return contentType; }
JavaScript
function readHeader(parts, index) { var header = ""; while ($.trim(parts[index]) !== "" && index < parts.length) { header = header.concat(parts[index], "\n"); index++; } return header; }
function readHeader(parts, index) { var header = ""; while ($.trim(parts[index]) !== "" && index < parts.length) { header = header.concat(parts[index], "\n"); index++; } return header; }
JavaScript
function Navbar() { return ( <nav class="navbar sticky-top navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/">Nick Leoni</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class="nav-link" href="./portfolio">Portfolio </a> </li> <li class="nav-item"> <a class="nav-link" href="./contact">Contact</a> </li> </ul> </div> </nav> ); }
function Navbar() { return ( <nav class="navbar sticky-top navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/">Nick Leoni</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class="nav-link" href="./portfolio">Portfolio </a> </li> <li class="nav-item"> <a class="nav-link" href="./contact">Contact</a> </li> </ul> </div> </nav> ); }
JavaScript
function process( object = all(), callback = rule => rule ) { const readRules = list => { if (hasRules(list)) { [...list.cssRules].forEach(rule => { callback(rule) if (hasRules(rule)) { readRules(rule) } }) } } if (Array.isArray(object)) { object.map(child => process(child, callback)) } else { readRules(object) } return object }
function process( object = all(), callback = rule => rule ) { const readRules = list => { if (hasRules(list)) { [...list.cssRules].forEach(rule => { callback(rule) if (hasRules(rule)) { readRules(rule) } }) } } if (Array.isArray(object)) { object.map(child => process(child, callback)) } else { readRules(object) } return object }
JavaScript
function remove( object = parse() ) { if (Array.isArray(object)) { object.map(remove) } else if (hasRules(object)) { [...object.cssRules].map(remove) } else if (object.parentRule) { object.parentRule.deleteRule( [...object.parentRule.cssRules].indexOf(object) ) } else if (object.parentStyleSheet) { object.parentStyleSheet.deleteRule( [...object.parentStyleSheet.cssRules].indexOf(object) ) } return object }
function remove( object = parse() ) { if (Array.isArray(object)) { object.map(remove) } else if (hasRules(object)) { [...object.cssRules].map(remove) } else if (object.parentRule) { object.parentRule.deleteRule( [...object.parentRule.cssRules].indexOf(object) ) } else if (object.parentStyleSheet) { object.parentStyleSheet.deleteRule( [...object.parentStyleSheet.cssRules].indexOf(object) ) } return object }
JavaScript
function all() { return [...document.styleSheets].map(stylesheet => { try { stylesheet.cssRules } catch(error) { return null } return stylesheet }).filter(hasRules) }
function all() { return [...document.styleSheets].map(stylesheet => { try { stylesheet.cssRules } catch(error) { return null } return stylesheet }).filter(hasRules) }
JavaScript
function filter( stylesheet = parse(), test = rule => rule ) { const output = {cssRules: []} process( stylesheet, rule => { if (test(rule)) { output.cssRules.push(rule) } } ) return output }
function filter( stylesheet = parse(), test = rule => rule ) { const output = {cssRules: []} process( stylesheet, rule => { if (test(rule)) { output.cssRules.push(rule) } } ) return output }
JavaScript
function selector( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { if (option) { return rule.selectorText && rule.selectorText.trim() === string } else { return rule.selectorText && rule.selectorText.includes(string) } } ) ).filter(hasRules) }
function selector( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { if (option) { return rule.selectorText && rule.selectorText.trim() === string } else { return rule.selectorText && rule.selectorText.includes(string) } } ) ).filter(hasRules) }
JavaScript
function property( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { return rule.style && [...rule.style].some(property => { if (option) { return property.trim() === string } else { return property.includes(string) } }) } ) ).filter(hasRules) }
function property( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { return rule.style && [...rule.style].some(property => { if (option) { return property.trim() === string } else { return property.includes(string) } }) } ) ).filter(hasRules) }
JavaScript
function value( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { return rule.style && [...rule.style].some(prop => { if (option) { return rule.style.getPropertyValue(prop).trim() === string } else { return rule.style.getPropertyValue(prop).includes(string) } }) } ) ).filter(hasRules) }
function value( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { return rule.style && [...rule.style].some(prop => { if (option) { return rule.style.getPropertyValue(prop).trim() === string } else { return rule.style.getPropertyValue(prop).includes(string) } }) } ) ).filter(hasRules) }
JavaScript
function query( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { if (option) { return rule.media && rule.media.mediaText.trim() === string } else { return rule.media && rule.media.mediaText.includes(string) } } ) ).filter(hasRules) }
function query( string = '', option = false, list = all() ) { if (list.cssRules) { list = [list] } return list.map(stylesheet => filter( stylesheet, rule => { if (option) { return rule.media && rule.media.mediaText.trim() === string } else { return rule.media && rule.media.mediaText.includes(string) } } ) ).filter(hasRules) }
JavaScript
buildParamsHeader(params) { let paramsArray = ["CYPHER"]; for (var key in params) { let value = this.paramToString(params[key]); paramsArray.push(`${key}=${value}`); } paramsArray.push(" "); return paramsArray.join(" "); }
buildParamsHeader(params) { let paramsArray = ["CYPHER"]; for (var key in params) { let value = this.paramToString(params[key]); paramsArray.push(`${key}=${value}`); } paramsArray.push(" "); return paramsArray.join(" "); }
JavaScript
async labels() { if (this._labelsPromise == undefined) { this._labelsPromise = this.callProcedure("db.labels").then( response => { return this._extractStrings(response); } ); this._labels = await this._labelsPromise; this._labelsPromise = undefined; } else { await this._labelsPromise; } }
async labels() { if (this._labelsPromise == undefined) { this._labelsPromise = this.callProcedure("db.labels").then( response => { return this._extractStrings(response); } ); this._labels = await this._labelsPromise; this._labelsPromise = undefined; } else { await this._labelsPromise; } }
JavaScript
async relationshipTypes() { if (this._relationshipPromise == undefined) { this._relationshipPromise = this.callProcedure( "db.relationshipTypes" ).then(response => { return this._extractStrings(response); }); this._relationshipTypes = await this._relationshipPromise; this._relationshipPromise = undefined; } else { await this._relationshipPromise; } }
async relationshipTypes() { if (this._relationshipPromise == undefined) { this._relationshipPromise = this.callProcedure( "db.relationshipTypes" ).then(response => { return this._extractStrings(response); }); this._relationshipTypes = await this._relationshipPromise; this._relationshipPromise = undefined; } else { await this._relationshipPromise; } }
JavaScript
async propertyKeys() { if (this._propertyPromise == undefined) { this._propertyPromise = this.callProcedure("db.propertyKeys").then( response => { return this._extractStrings(response); } ); this._properties = await this._propertyPromise; this._propertyPromise = undefined; } else { await this._propertyPromise; } }
async propertyKeys() { if (this._propertyPromise == undefined) { this._propertyPromise = this.callProcedure("db.propertyKeys").then( response => { return this._extractStrings(response); } ); this._properties = await this._propertyPromise; this._propertyPromise = undefined; } else { await this._propertyPromise; } }
JavaScript
function arreglarNavLinks() { if(window.innerWidth >= 900) { navLinks.classList.remove("mostrar"); } }
function arreglarNavLinks() { if(window.innerWidth >= 900) { navLinks.classList.remove("mostrar"); } }
JavaScript
async function handleRequest(request) { let url = new URL(request.url); if (url.pathname == "/") { return handleRoot(url); } else if (url.pathname == "/favicon.ico") { return handle404(); } else { return handleDrama(url); } }
async function handleRequest(request) { let url = new URL(request.url); if (url.pathname == "/") { return handleRoot(url); } else if (url.pathname == "/favicon.ico") { return handle404(); } else { return handleDrama(url); } }
JavaScript
function LevelUP (location, options, callback) { if (!(this instanceof LevelUP)) return new LevelUP(location, options, callback) var error EventEmitter.call(this) this.setMaxListeners(Infinity) if (typeof location == 'function') { options = typeof options == 'object' ? options : {} options.db = location location = null } else if (typeof location == 'object' && typeof location.db == 'function') { options = location location = null } if (typeof options == 'function') { callback = options options = {} } if ((!options || typeof options.db != 'function') && typeof location != 'string') { error = new InitializationError( 'Must provide a location for the database') if (callback) { return process.nextTick(function () { callback(error) }) } throw error } options = getOptions(this, options) this.options = extend(defaultOptions, options) this._status = 'new' // set this.location as enumerable but not configurable or writable prr(this, 'location', location, 'e') this.open(callback) }
function LevelUP (location, options, callback) { if (!(this instanceof LevelUP)) return new LevelUP(location, options, callback) var error EventEmitter.call(this) this.setMaxListeners(Infinity) if (typeof location == 'function') { options = typeof options == 'object' ? options : {} options.db = location location = null } else if (typeof location == 'object' && typeof location.db == 'function') { options = location location = null } if (typeof options == 'function') { callback = options options = {} } if ((!options || typeof options.db != 'function') && typeof location != 'string') { error = new InitializationError( 'Must provide a location for the database') if (callback) { return process.nextTick(function () { callback(error) }) } throw error } options = getOptions(this, options) this.options = extend(defaultOptions, options) this._status = 'new' // set this.location as enumerable but not configurable or writable prr(this, 'location', location, 'e') this.open(callback) }
JavaScript
function TimeSeries(options) { this.options = Util.extend({}, TimeSeries.defaultOptions, options); this.disabled = false; this.clear(); }
function TimeSeries(options) { this.options = Util.extend({}, TimeSeries.defaultOptions, options); this.disabled = false; this.clear(); }
JavaScript
function SmoothieChart(options) { this.options = Util.extend({}, SmoothieChart.defaultChartOptions, options); this.seriesSet = []; this.currentValueRange = 1; this.currentVisMinValue = 0; this.lastRenderTimeMillis = 0; this.lastChartTimestamp = 0; this.mousemove = this.mousemove.bind(this); this.mouseout = this.mouseout.bind(this); }
function SmoothieChart(options) { this.options = Util.extend({}, SmoothieChart.defaultChartOptions, options); this.seriesSet = []; this.currentValueRange = 1; this.currentVisMinValue = 0; this.lastRenderTimeMillis = 0; this.lastChartTimestamp = 0; this.mousemove = this.mousemove.bind(this); this.mouseout = this.mouseout.bind(this); }
JavaScript
_markDefs() { const nodeDefs = this.json.nodes || []; const skinDefs = this.json.skins || []; const meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a THREE.Bone or an // THREE.Object3D. Use the skins' joint references to mark bones. for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { const joints = skinDefs[ skinIndex ].joints; for ( let i = 0, il = joints.length; i < il; i ++ ) { nodeDefs[ joints[ i ] ].isBone = true; } } // Iterate over all nodes, marking references to shared resources, // as well as skeleton joints. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { const nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.mesh !== undefined ) { this._addNodeRef( this.meshCache, nodeDef.mesh ); // Nothing in the mesh definition indicates whether it is // a THREE.SkinnedMesh or THREE.Mesh. Use the node's mesh reference // to mark THREE.SkinnedMesh if node has skin. if ( nodeDef.skin !== undefined ) { meshDefs[ nodeDef.mesh ].isSkinnedMesh = true; } } if ( nodeDef.camera !== undefined ) { this._addNodeRef( this.cameraCache, nodeDef.camera ); } } }
_markDefs() { const nodeDefs = this.json.nodes || []; const skinDefs = this.json.skins || []; const meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a THREE.Bone or an // THREE.Object3D. Use the skins' joint references to mark bones. for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { const joints = skinDefs[ skinIndex ].joints; for ( let i = 0, il = joints.length; i < il; i ++ ) { nodeDefs[ joints[ i ] ].isBone = true; } } // Iterate over all nodes, marking references to shared resources, // as well as skeleton joints. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { const nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.mesh !== undefined ) { this._addNodeRef( this.meshCache, nodeDef.mesh ); // Nothing in the mesh definition indicates whether it is // a THREE.SkinnedMesh or THREE.Mesh. Use the node's mesh reference // to mark THREE.SkinnedMesh if node has skin. if ( nodeDef.skin !== undefined ) { meshDefs[ nodeDef.mesh ].isSkinnedMesh = true; } } if ( nodeDef.camera !== undefined ) { this._addNodeRef( this.cameraCache, nodeDef.camera ); } } }
JavaScript
_addNodeRef( cache, index ) { if ( index === undefined ) return; if ( cache.refs[ index ] === undefined ) { cache.refs[ index ] = cache.uses[ index ] = 0; } cache.refs[ index ] ++; }
_addNodeRef( cache, index ) { if ( index === undefined ) return; if ( cache.refs[ index ] === undefined ) { cache.refs[ index ] = cache.uses[ index ] = 0; } cache.refs[ index ] ++; }
JavaScript
_getNodeRef( cache, index, object ) { if ( cache.refs[ index ] <= 1 ) return object; const ref = object.clone(); ref.name += '_instance_' + cache.uses[ index ] ++; return ref; }
_getNodeRef( cache, index, object ) { if ( cache.refs[ index ] <= 1 ) return object; const ref = object.clone(); ref.name += '_instance_' + cache.uses[ index ] ++; return ref; }
JavaScript
createUniqueName( originalName ) { const sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' ); let name = sanitizedName; for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) { name = sanitizedName + '_' + i; } this.nodeNamesUsed[ name ] = true; return name; }
createUniqueName( originalName ) { const sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' ); let name = sanitizedName; for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) { name = sanitizedName + '_' + i; } this.nodeNamesUsed[ name ] = true; return name; }
JavaScript
function checkKey(e) { e = e || window.event; if(e.keyCode==37){ console.log("prev audio track"); playlist.prev(); } else if(e.keyCode==39){ console.log("next audio track"); playlist.next(); } }
function checkKey(e) { e = e || window.event; if(e.keyCode==37){ console.log("prev audio track"); playlist.prev(); } else if(e.keyCode==39){ console.log("next audio track"); playlist.next(); } }
JavaScript
function BiosampleSummaryString(biosample, supressOrganism) { const organismName = biosample.organism.scientific_name; const organismlessSummary = biosample.summary.replace(`${organismName} `, ''); if (supressOrganism) { return <span>{organismlessSummary}</span>; } return <span><i>{biosample.organism.scientific_name}</i> {organismlessSummary}</span>; }
function BiosampleSummaryString(biosample, supressOrganism) { const organismName = biosample.organism.scientific_name; const organismlessSummary = biosample.summary.replace(`${organismName} `, ''); if (supressOrganism) { return <span>{organismlessSummary}</span>; } return <span><i>{biosample.organism.scientific_name}</i> {organismlessSummary}</span>; }
JavaScript
function CollectBiosampleDocs(biosample) { // Collect up the various biosample documents let protocolDocuments = []; if (biosample.documents && biosample.documents.length) { protocolDocuments = _.uniq(biosample.documents); } let characterizations = []; if (biosample.characterizations && biosample.characterizations.length) { characterizations = _.uniq(biosample.characterizations); } let donorDocuments = []; let donorCharacterizations = []; if (biosample.donor) { if (biosample.donor.characterizations && biosample.donor.characterizations.length) { donorCharacterizations = biosample.donor.characterizations; } if (biosample.donor.documents && biosample.donor.documents.length) { donorDocuments = biosample.donor.documents; } } let treatmentDocuments = []; if (biosample.treatments && biosample.treatments.length) { treatmentDocuments = biosample.treatments.reduce((allDocs, treatment) => ((treatment.documents && treatment.documents.length) ? allDocs.concat(treatment.documents) : allDocs), []); } // Put together the document list for rendering // Compile the document list const combinedDocuments = _.uniq([].concat( protocolDocuments, characterizations, donorDocuments, donorCharacterizations, treatmentDocuments, )); return combinedDocuments; }
function CollectBiosampleDocs(biosample) { // Collect up the various biosample documents let protocolDocuments = []; if (biosample.documents && biosample.documents.length) { protocolDocuments = _.uniq(biosample.documents); } let characterizations = []; if (biosample.characterizations && biosample.characterizations.length) { characterizations = _.uniq(biosample.characterizations); } let donorDocuments = []; let donorCharacterizations = []; if (biosample.donor) { if (biosample.donor.characterizations && biosample.donor.characterizations.length) { donorCharacterizations = biosample.donor.characterizations; } if (biosample.donor.documents && biosample.donor.documents.length) { donorDocuments = biosample.donor.documents; } } let treatmentDocuments = []; if (biosample.treatments && biosample.treatments.length) { treatmentDocuments = biosample.treatments.reduce((allDocs, treatment) => ((treatment.documents && treatment.documents.length) ? allDocs.concat(treatment.documents) : allDocs), []); } // Put together the document list for rendering // Compile the document list const combinedDocuments = _.uniq([].concat( protocolDocuments, characterizations, donorDocuments, donorCharacterizations, treatmentDocuments, )); return combinedDocuments; }
JavaScript
function fileStatusList(session, sessionProperties) { const loggedIn = !!(session && session['auth.userid']); const adminUser = !!(sessionProperties && sessionProperties.admin); // These statuses are the only ones logged-out users can see. let statuses = [ 'released', 'revoked', 'archived', ]; // If the user's logged in, add in more statuses. if (loggedIn) { statuses = statuses.concat([ 'uploading', 'in progress', 'content error', 'upload failed', ]); } // If the user's logged in as an admin, add in the last statuses. if (adminUser) { statuses = statuses.concat([ 'deleted', 'replaced', ]); } return statuses.concat(['status unknown']); }
function fileStatusList(session, sessionProperties) { const loggedIn = !!(session && session['auth.userid']); const adminUser = !!(sessionProperties && sessionProperties.admin); // These statuses are the only ones logged-out users can see. let statuses = [ 'released', 'revoked', 'archived', ]; // If the user's logged in, add in more statuses. if (loggedIn) { statuses = statuses.concat([ 'uploading', 'in progress', 'content error', 'upload failed', ]); } // If the user's logged in as an admin, add in the last statuses. if (adminUser) { statuses = statuses.concat([ 'deleted', 'replaced', ]); } return statuses.concat(['status unknown']); }
JavaScript
function requestObjects(atIds, uri, filteringObjects) { const chunkSize = 100; // Maximum # of files to search for at once const filteringFileIds = {}; // @ids of files we've searched for and don't need retrieval let filteredObjectIds = {}; // @ids of files we need to retrieve // Make a searchable object of file IDs for files to filter out of our list. if (filteringObjects && filteringObjects.length) { filteringObjects.forEach((filteringObject) => { filteringFileIds[filteringObject['@id']] = filteringObject; }); // Filter the given file @ids to exclude those files we already have in data.@graph, // just so we don't use bandwidth getting things we already have. filteredObjectIds = atIds.filter(atId => !filteringFileIds[atId]); } else { // The caller didn't supply an array of files to filter out, so filtered files are just // all of them. filteredObjectIds = atIds; } // Break fileIds into an array of arrays of <= `chunkSize` @ids so we don't generate search // URLs that are too long for the server to handle. const objectChunks = []; for (let start = 0, chunkIndex = 0; start < filteredObjectIds.length; start += chunkSize, chunkIndex += 1) { objectChunks[chunkIndex] = filteredObjectIds.slice(start, start + chunkSize); } // Going to send out all search chunk GET requests at once, and then wait for all of them to // complete. return Promise.all(objectChunks.map((objectChunk) => { // Build URL containing file search for specific files for each chunk of files. const url = uri.concat(objectChunk.reduce((combined, current) => `${combined}&@id=${current}`, '')); return fetch(url, { method: 'GET', headers: { Accept: 'application/json', }, }).then((response) => { // Convert each response response to JSON if (response.ok) { return response.json(); } return Promise.resolve(null); }); })).then((chunks) => { // All search chunks have resolved or errored. We get an array of search results in // `chunks` -- one per chunk. Now collect their files from their @graphs into one array of // files and return them as the promise result. if (chunks && chunks.length) { return chunks.reduce((objects, chunk) => (chunk && chunk['@graph'].length ? objects.concat(chunk['@graph']) : objects), []); } // Didn't get any good chucks back, so just return no results. return []; }); }
function requestObjects(atIds, uri, filteringObjects) { const chunkSize = 100; // Maximum # of files to search for at once const filteringFileIds = {}; // @ids of files we've searched for and don't need retrieval let filteredObjectIds = {}; // @ids of files we need to retrieve // Make a searchable object of file IDs for files to filter out of our list. if (filteringObjects && filteringObjects.length) { filteringObjects.forEach((filteringObject) => { filteringFileIds[filteringObject['@id']] = filteringObject; }); // Filter the given file @ids to exclude those files we already have in data.@graph, // just so we don't use bandwidth getting things we already have. filteredObjectIds = atIds.filter(atId => !filteringFileIds[atId]); } else { // The caller didn't supply an array of files to filter out, so filtered files are just // all of them. filteredObjectIds = atIds; } // Break fileIds into an array of arrays of <= `chunkSize` @ids so we don't generate search // URLs that are too long for the server to handle. const objectChunks = []; for (let start = 0, chunkIndex = 0; start < filteredObjectIds.length; start += chunkSize, chunkIndex += 1) { objectChunks[chunkIndex] = filteredObjectIds.slice(start, start + chunkSize); } // Going to send out all search chunk GET requests at once, and then wait for all of them to // complete. return Promise.all(objectChunks.map((objectChunk) => { // Build URL containing file search for specific files for each chunk of files. const url = uri.concat(objectChunk.reduce((combined, current) => `${combined}&@id=${current}`, '')); return fetch(url, { method: 'GET', headers: { Accept: 'application/json', }, }).then((response) => { // Convert each response response to JSON if (response.ok) { return response.json(); } return Promise.resolve(null); }); })).then((chunks) => { // All search chunks have resolved or errored. We get an array of search results in // `chunks` -- one per chunk. Now collect their files from their @graphs into one array of // files and return them as the promise result. if (chunks && chunks.length) { return chunks.reduce((objects, chunk) => (chunk && chunk['@graph'].length ? objects.concat(chunk['@graph']) : objects), []); } // Didn't get any good chucks back, so just return no results. return []; }); }
JavaScript
function donorDiversity(dataset) { let diversity = 'none'; if (dataset.related_datasets && dataset.related_datasets.length) { // Get all non-deleted related experiments; empty array if none. const experiments = dataset.related_datasets.filter(experiment => experiment.status !== 'deleted'); // From list list of non-deleted experiments, get all non-deleted replicates into one // array. if (experiments.length) { // Make an array of replicate arrays, one replicate array per experiment. Only include // non-deleted replicates. const replicatesByExperiment = experiments.map(experiment => ( (experiment.replicates && experiment.replicates.length) ? experiment.replicates.filter(replicate => replicate.status !== 'deleted') : []), ); // Merge all replicate arrays into one non-deleted replicate array. const replicates = replicatesByExperiment.reduce((replicateCollection, replicatesForExperiment) => replicateCollection.concat(replicatesForExperiment), []); // Look at the donors in each replicate's biosample. If we see at least two different // donors, we know we have a composite. If only one unique donor after examining all // donors, we have a single. "None" if no donors found in all replicates. if (replicates.length) { const donorAtIdCollection = []; replicates.every((replicate) => { if (replicate.library && replicate.library.status !== 'deleted' && replicate.library.biosample && replicate.library.biosample.status !== 'deleted' && replicate.library.biosample.donor && replicate.library.biosample.donor.status !== 'deleted') { const donorAccession = replicate.library.biosample.donor.accession; // If we haven't yet seen this donor @id, add it to our collection if (donorAtIdCollection.indexOf(donorAccession) === -1) { donorAtIdCollection.push(donorAccession); } // If we have two, we know have a composite, and we can exit the loop by // returning false, which makes the replicates.every function end. return donorAtIdCollection.length !== 2; } // No donor to examine in this replicate. Keep the `every` loop going. return true; }); // Now determine the donor diversity. if (donorAtIdCollection.length > 1) { diversity = 'composite'; } else if (donorAtIdCollection.length === 1) { diversity = 'single'; } // Else keep its original value of 'none'. } } } return diversity; }
function donorDiversity(dataset) { let diversity = 'none'; if (dataset.related_datasets && dataset.related_datasets.length) { // Get all non-deleted related experiments; empty array if none. const experiments = dataset.related_datasets.filter(experiment => experiment.status !== 'deleted'); // From list list of non-deleted experiments, get all non-deleted replicates into one // array. if (experiments.length) { // Make an array of replicate arrays, one replicate array per experiment. Only include // non-deleted replicates. const replicatesByExperiment = experiments.map(experiment => ( (experiment.replicates && experiment.replicates.length) ? experiment.replicates.filter(replicate => replicate.status !== 'deleted') : []), ); // Merge all replicate arrays into one non-deleted replicate array. const replicates = replicatesByExperiment.reduce((replicateCollection, replicatesForExperiment) => replicateCollection.concat(replicatesForExperiment), []); // Look at the donors in each replicate's biosample. If we see at least two different // donors, we know we have a composite. If only one unique donor after examining all // donors, we have a single. "None" if no donors found in all replicates. if (replicates.length) { const donorAtIdCollection = []; replicates.every((replicate) => { if (replicate.library && replicate.library.status !== 'deleted' && replicate.library.biosample && replicate.library.biosample.status !== 'deleted' && replicate.library.biosample.donor && replicate.library.biosample.donor.status !== 'deleted') { const donorAccession = replicate.library.biosample.donor.accession; // If we haven't yet seen this donor @id, add it to our collection if (donorAtIdCollection.indexOf(donorAccession) === -1) { donorAtIdCollection.push(donorAccession); } // If we have two, we know have a composite, and we can exit the loop by // returning false, which makes the replicates.every function end. return donorAtIdCollection.length !== 2; } // No donor to examine in this replicate. Keep the `every` loop going. return true; }); // Now determine the donor diversity. if (donorAtIdCollection.length > 1) { diversity = 'composite'; } else if (donorAtIdCollection.length === 1) { diversity = 'single'; } // Else keep its original value of 'none'. } } } return diversity; }
JavaScript
function sortProcessedPagedFiles(files) { // Split the list into two groups for basic sorting first by those with accessions, // then those with external_accessions. const accessionList = _(files).groupBy(file => (file.accession ? 'accession' : 'external')); // Start by sorting the accessioned files. let sortedAccession = []; let sortedExternal = []; if (accessionList.accession && accessionList.accession.length) { sortedAccession = accessionList.accession.sort((a, b) => (a.accession > b.accession ? 1 : (a.accession < b.accession ? -1 : 0))); } // Now sort the external_accession files if (accessionList.external && accessionList.external.length) { sortedExternal = accessionList.external.sort((a, b) => (a.title > b.title ? 1 : (a.title < b.title ? -1 : 0))); } return sortedAccession.concat(sortedExternal); }
function sortProcessedPagedFiles(files) { // Split the list into two groups for basic sorting first by those with accessions, // then those with external_accessions. const accessionList = _(files).groupBy(file => (file.accession ? 'accession' : 'external')); // Start by sorting the accessioned files. let sortedAccession = []; let sortedExternal = []; if (accessionList.accession && accessionList.accession.length) { sortedAccession = accessionList.accession.sort((a, b) => (a.accession > b.accession ? 1 : (a.accession < b.accession ? -1 : 0))); } // Now sort the external_accession files if (accessionList.external && accessionList.external.length) { sortedExternal = accessionList.external.sort((a, b) => (a.title > b.title ? 1 : (a.title < b.title ? -1 : 0))); } return sortedAccession.concat(sortedExternal); }
JavaScript
currentPageFiles() { if (this.allFileIds && this.allFileIds.length) { const start = this.state.currentPage * PagedFileTableMax; return this.allFileIds.slice(start, start + PagedFileTableMax); } return []; }
currentPageFiles() { if (this.allFileIds && this.allFileIds.length) { const start = this.state.currentPage * PagedFileTableMax; return this.allFileIds.slice(start, start + PagedFileTableMax); } return []; }
JavaScript
handleEsc(e) { if ((!this.props.actuator || this.state.modalOpen) && e.keyCode === 27) { if (this.props.closeModal) { this.props.closeModal(); } else { this.closeModal(); } } }
handleEsc(e) { if ((!this.props.actuator || this.state.modalOpen) && e.keyCode === 27) { if (this.props.closeModal) { this.props.closeModal(); } else { this.closeModal(); } } }
JavaScript
closeModal() { this.setState({ modalOpen: false }); // Remove class from body element to make modal-backdrop div visible document.body.classList.remove('modal-open'); }
closeModal() { this.setState({ modalOpen: false }); // Remove class from body element to make modal-backdrop div visible document.body.classList.remove('modal-open'); }
JavaScript
function generateQuery(chosenOrganisms, searchTerm) { // Make the base query. let query = ''; // Add all the selected organisms, if any if (chosenOrganisms.length) { const queryStrings = { HUMAN: `${searchTerm}Homo+sapiens`, // human MOUSE: `${searchTerm}Mus+musculus`, // mouse WORM: `${searchTerm}Caenorhabditis+elegans`, // worm FLY: `${searchTerm}Drosophila+melanogaster&${searchTerm}Drosophila+pseudoobscura&${searchTerm}Drosophila+simulans&${searchTerm}Drosophila+mojavensis&${searchTerm}Drosophila+ananassae&${searchTerm}Drosophila+virilis&${searchTerm}Drosophila+yakuba`, }; const organismQueries = chosenOrganisms.map(organism => queryStrings[organism]); query += `&${organismQueries.join('&')}`; } return query; }
function generateQuery(chosenOrganisms, searchTerm) { // Make the base query. let query = ''; // Add all the selected organisms, if any if (chosenOrganisms.length) { const queryStrings = { HUMAN: `${searchTerm}Homo+sapiens`, // human MOUSE: `${searchTerm}Mus+musculus`, // mouse WORM: `${searchTerm}Caenorhabditis+elegans`, // worm FLY: `${searchTerm}Drosophila+melanogaster&${searchTerm}Drosophila+pseudoobscura&${searchTerm}Drosophila+simulans&${searchTerm}Drosophila+mojavensis&${searchTerm}Drosophila+ananassae&${searchTerm}Drosophila+virilis&${searchTerm}Drosophila+yakuba`, }; const organismQueries = chosenOrganisms.map(organism => queryStrings[organism]); query += `&${organismQueries.join('&')}`; } return query; }
JavaScript
function drawDonutCenter(chart) { const canvasId = chart.chart.canvas.id; const width = chart.chart.width; const height = chart.chart.height; const ctx = chart.chart.ctx; // Undraws donut centers for Cumulative Line Chart and Status Stacked Bar Chart. if (canvasId === 'myGraph' || canvasId === 'status-chart-experiments-chart') { ctx.clearRect(0, 0, width, height); } else { const data = chart.data.datasets[0].data; if (data.length) { ctx.fillStyle = '#000000'; ctx.restore(); const fontSize = (height / 114).toFixed(2); ctx.font = `${fontSize}em sans-serif`; ctx.textBaseline = 'middle'; const total = data.reduce((prev, curr) => prev + curr); const textX = Math.round((width - ctx.measureText(total).width) / 2); const textY = height / 2; ctx.clearRect(0, 0, width, height); ctx.fillText(total, textX, textY); ctx.save(); } } }
function drawDonutCenter(chart) { const canvasId = chart.chart.canvas.id; const width = chart.chart.width; const height = chart.chart.height; const ctx = chart.chart.ctx; // Undraws donut centers for Cumulative Line Chart and Status Stacked Bar Chart. if (canvasId === 'myGraph' || canvasId === 'status-chart-experiments-chart') { ctx.clearRect(0, 0, width, height); } else { const data = chart.data.datasets[0].data; if (data.length) { ctx.fillStyle = '#000000'; ctx.restore(); const fontSize = (height / 114).toFixed(2); ctx.font = `${fontSize}em sans-serif`; ctx.textBaseline = 'middle'; const total = data.reduce((prev, curr) => prev + curr); const textX = Math.round((width - ctx.measureText(total).width) / 2); const textY = height / 2; ctx.clearRect(0, 0, width, height); ctx.fillText(total, textX, textY); ctx.save(); } } }
JavaScript
function createDoughnutChart(chartId, values, labels, colors, baseSearchUri, navigate) { return new Promise((resolve) => { require.ensure(['chart.js'], (require) => { const Chart = require('chart.js'); // adding total doc count to middle of donut // http://stackoverflow.com/questions/20966817/how-to-add-text-inside-the-doughnut-chart-using-chart-js/24671908 Chart.pluginService.register({ beforeDraw: drawDonutCenter, }); // Create the chart. const canvas = document.getElementById(`${chartId}-chart`); const parent = document.getElementById(chartId); canvas.width = parent.offsetWidth; canvas.height = parent.offsetHeight; canvas.style.width = `${parent.offsetWidth}px`; canvas.style.height = `${parent.offsetHeight}px`; const ctx = canvas.getContext('2d'); const chart = new Chart(ctx, { type: 'doughnut', data: { labels, datasets: [{ data: values, backgroundColor: colors, }], }, options: { maintainAspectRatio: false, responsive: true, legend: { display: false, }, animation: { duration: 200, }, legendCallback: (chartInstance) => { const chartData = chartInstance.data.datasets[0].data; const chartColors = chartInstance.data.datasets[0].backgroundColor; const chartLabels = chartInstance.data.labels; const text = []; text.push('<ul>'); for (let i = 0; i < chartData.length; i += 1) { if (chartData[i]) { text.push(`<li><a href="${baseSearchUri}${chartLabels[i]}">`); text.push(`<i class="icon icon-circle chart-legend-chip" aria-hidden="true" style="color:${chartColors[i]}"></i>`); text.push(`<span class="chart-legend-label">${chartLabels[i]}</span>`); text.push('</a></li>'); } } text.push('</ul>'); return text.join(''); }, onClick: function onClick(e) { // React to clicks on pie sections const activePoints = chart.getElementAtEvent(e); // chart.options.onClick.baseSearchUri is created or altered based on user input of selected Genus Buttons // Each type of Object (e.g. Experiments, Annotations, Biosample, AntibodyLot) has a unique // query string for the corresponding report search -- cannot simply append something // to end of baseSearchUri, as baseSearchUri ends with {searchtype}= // so, query string specifying genus must end up somewhere in the middle of the string // that is baseSearchUri. // chart.options.onClick.baseSearchUri must be defined in the type of chart (StatusChart, CategoryChart) // that is passed to the createDonutChart or createBarChart functions because cannot directly // make changes to the param baseSearchUri in updateChart(). if (activePoints[0]) { // if click on wrong area, do nothing const clickedElementIndex = activePoints[0]._index; const term = chart.data.labels[clickedElementIndex]; if (chart.options.onClick.baseSearchUri) { navigate(`${chart.options.onClick.baseSearchUri}${globals.encodedURIComponent(term)}`); } else { navigate(`${baseSearchUri}${globals.encodedURIComponent(term)}`); } } }, }, }); document.getElementById(`${chartId}-legend`).innerHTML = chart.generateLegend(); // Resolve the webpack loader promise with the chart instance. resolve(chart); }, 'chartjs'); }); }
function createDoughnutChart(chartId, values, labels, colors, baseSearchUri, navigate) { return new Promise((resolve) => { require.ensure(['chart.js'], (require) => { const Chart = require('chart.js'); // adding total doc count to middle of donut // http://stackoverflow.com/questions/20966817/how-to-add-text-inside-the-doughnut-chart-using-chart-js/24671908 Chart.pluginService.register({ beforeDraw: drawDonutCenter, }); // Create the chart. const canvas = document.getElementById(`${chartId}-chart`); const parent = document.getElementById(chartId); canvas.width = parent.offsetWidth; canvas.height = parent.offsetHeight; canvas.style.width = `${parent.offsetWidth}px`; canvas.style.height = `${parent.offsetHeight}px`; const ctx = canvas.getContext('2d'); const chart = new Chart(ctx, { type: 'doughnut', data: { labels, datasets: [{ data: values, backgroundColor: colors, }], }, options: { maintainAspectRatio: false, responsive: true, legend: { display: false, }, animation: { duration: 200, }, legendCallback: (chartInstance) => { const chartData = chartInstance.data.datasets[0].data; const chartColors = chartInstance.data.datasets[0].backgroundColor; const chartLabels = chartInstance.data.labels; const text = []; text.push('<ul>'); for (let i = 0; i < chartData.length; i += 1) { if (chartData[i]) { text.push(`<li><a href="${baseSearchUri}${chartLabels[i]}">`); text.push(`<i class="icon icon-circle chart-legend-chip" aria-hidden="true" style="color:${chartColors[i]}"></i>`); text.push(`<span class="chart-legend-label">${chartLabels[i]}</span>`); text.push('</a></li>'); } } text.push('</ul>'); return text.join(''); }, onClick: function onClick(e) { // React to clicks on pie sections const activePoints = chart.getElementAtEvent(e); // chart.options.onClick.baseSearchUri is created or altered based on user input of selected Genus Buttons // Each type of Object (e.g. Experiments, Annotations, Biosample, AntibodyLot) has a unique // query string for the corresponding report search -- cannot simply append something // to end of baseSearchUri, as baseSearchUri ends with {searchtype}= // so, query string specifying genus must end up somewhere in the middle of the string // that is baseSearchUri. // chart.options.onClick.baseSearchUri must be defined in the type of chart (StatusChart, CategoryChart) // that is passed to the createDonutChart or createBarChart functions because cannot directly // make changes to the param baseSearchUri in updateChart(). if (activePoints[0]) { // if click on wrong area, do nothing const clickedElementIndex = activePoints[0]._index; const term = chart.data.labels[clickedElementIndex]; if (chart.options.onClick.baseSearchUri) { navigate(`${chart.options.onClick.baseSearchUri}${globals.encodedURIComponent(term)}`); } else { navigate(`${baseSearchUri}${globals.encodedURIComponent(term)}`); } } }, }, }); document.getElementById(`${chartId}-legend`).innerHTML = chart.generateLegend(); // Resolve the webpack loader promise with the chart instance. resolve(chart); }, 'chartjs'); }); }
JavaScript
function createBarChart(chartId, data, colors, replicateLabels, baseSearchUri, navigate) { return new Promise((resolve) => { require.ensure(['chart.js'], (require) => { const Chart = require('chart.js'); const datasets = []; if (data.unreplicatedDataset.some(x => x > 0)) { datasets.push({ label: 'unreplicated', data: data.unreplicatedDataset, backgroundColor: colors[0] }); } if (data.isogenicDataset.some(x => x > 0)) { datasets.push({ label: 'isogenic', data: data.isogenicDataset, backgroundColor: colors[1] }); } if (data.anisogenicDataset.some(x => x > 0)) { datasets.push({ label: 'anisogenic', data: data.anisogenicDataset, backgroundColor: colors[2] }); } for (let i = 0; i < datasets.length; i += 1) { datasets[i].backgroundColor = colors[i]; } // Create the chart. const canvas = document.getElementById(`${chartId}-chart`); const parent = document.getElementById(chartId); canvas.width = parent.offsetWidth; canvas.height = parent.offsetHeight; canvas.style.width = `${parent.offsetWidth}px`; canvas.style.height = `${parent.offsetHeight}px`; const ctx = canvas.getContext('2d'); const chart = new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets, }, options: { maintainAspectRatio: false, responsive: true, legend: { display: false, }, scales: { xAxes: [{ scaleLabel: { display: false, }, gridLines: { }, stacked: true, }], yAxes: [{ gridLines: { display: false, color: '#fff', zeroLineColor: '#fff', zeroLineWidth: 0, }, stacked: true, }], }, animation: { duration: 200, }, legendCallback: (chartInstance) => { const LegendLabels = []; const dataColors = []; // If data array has value, add to legend for (let i = 0; i < datasets.length; i += 1) { LegendLabels.push(chartInstance.data.datasets[i].label); dataColors.push(chartInstance.data.datasets[i].backgroundColor); } const text = []; text.push('<ul>'); for (let i = 0; i < LegendLabels.length; i += 1) { if (LegendLabels[i]) { text.push(`<li><a href="${baseSearchUri}&replication_type=${LegendLabels[i]}">`); text.push(`<i class="icon icon-circle chart-legend-chip" aria-hidden="true" style="color:${dataColors[i]}"></i>`); text.push(`<span class="chart-legend-label">${LegendLabels[i]}</span>`); text.push('</a></li>'); } } text.push('</ul>'); return text.join(''); }, onClick: function onClick(e) { const activePoints = chart.getElementAtEvent(e); if (activePoints[0]) { // if click on wrong area, do nothing const clickedElementIndex = activePoints[0]._index; const clickedElementdataset = activePoints[0]._datasetIndex; const term = chart.data.labels[clickedElementIndex]; const item = chart.data.datasets[clickedElementdataset].label; // chart.options.onClick.baseSearchUri is created or altered based on user input of selected Genus Buttons // Each type of Object (e.g. Experiments, Annotations, Biosample, AntibodyLot) has a unique // query string for the corresponding report search -- cannot simply append something // to end of baseSearchUri, as baseSearchUri ends with {searchtype}= // so, query string specifying genus must end up somewhere in the middle of the string // that is baseSearchUri. // chart.options.onClick.baseSearchUri must be defined in the type of chart (StatusChart, CategoryChart) // that is passed to the createDonutChart or createBarChart functions because cannot directly // make changes to the param baseSearchUri in updateChart(). if (chart.options.onClick.baseSearchUri) { navigate(`${chart.options.onClick.baseSearchUri}&status=${globals.encodedURIComponent(term)}&replication_type=${item}`); } else { navigate(`${baseSearchUri}&status=${globals.encodedURIComponent(term)}&replication_type=${item}`); } } }, }, }); document.getElementById(`${chartId}-legend`).innerHTML = chart.generateLegend(); resolve(chart); }, 'chartjs'); }); }
function createBarChart(chartId, data, colors, replicateLabels, baseSearchUri, navigate) { return new Promise((resolve) => { require.ensure(['chart.js'], (require) => { const Chart = require('chart.js'); const datasets = []; if (data.unreplicatedDataset.some(x => x > 0)) { datasets.push({ label: 'unreplicated', data: data.unreplicatedDataset, backgroundColor: colors[0] }); } if (data.isogenicDataset.some(x => x > 0)) { datasets.push({ label: 'isogenic', data: data.isogenicDataset, backgroundColor: colors[1] }); } if (data.anisogenicDataset.some(x => x > 0)) { datasets.push({ label: 'anisogenic', data: data.anisogenicDataset, backgroundColor: colors[2] }); } for (let i = 0; i < datasets.length; i += 1) { datasets[i].backgroundColor = colors[i]; } // Create the chart. const canvas = document.getElementById(`${chartId}-chart`); const parent = document.getElementById(chartId); canvas.width = parent.offsetWidth; canvas.height = parent.offsetHeight; canvas.style.width = `${parent.offsetWidth}px`; canvas.style.height = `${parent.offsetHeight}px`; const ctx = canvas.getContext('2d'); const chart = new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets, }, options: { maintainAspectRatio: false, responsive: true, legend: { display: false, }, scales: { xAxes: [{ scaleLabel: { display: false, }, gridLines: { }, stacked: true, }], yAxes: [{ gridLines: { display: false, color: '#fff', zeroLineColor: '#fff', zeroLineWidth: 0, }, stacked: true, }], }, animation: { duration: 200, }, legendCallback: (chartInstance) => { const LegendLabels = []; const dataColors = []; // If data array has value, add to legend for (let i = 0; i < datasets.length; i += 1) { LegendLabels.push(chartInstance.data.datasets[i].label); dataColors.push(chartInstance.data.datasets[i].backgroundColor); } const text = []; text.push('<ul>'); for (let i = 0; i < LegendLabels.length; i += 1) { if (LegendLabels[i]) { text.push(`<li><a href="${baseSearchUri}&replication_type=${LegendLabels[i]}">`); text.push(`<i class="icon icon-circle chart-legend-chip" aria-hidden="true" style="color:${dataColors[i]}"></i>`); text.push(`<span class="chart-legend-label">${LegendLabels[i]}</span>`); text.push('</a></li>'); } } text.push('</ul>'); return text.join(''); }, onClick: function onClick(e) { const activePoints = chart.getElementAtEvent(e); if (activePoints[0]) { // if click on wrong area, do nothing const clickedElementIndex = activePoints[0]._index; const clickedElementdataset = activePoints[0]._datasetIndex; const term = chart.data.labels[clickedElementIndex]; const item = chart.data.datasets[clickedElementdataset].label; // chart.options.onClick.baseSearchUri is created or altered based on user input of selected Genus Buttons // Each type of Object (e.g. Experiments, Annotations, Biosample, AntibodyLot) has a unique // query string for the corresponding report search -- cannot simply append something // to end of baseSearchUri, as baseSearchUri ends with {searchtype}= // so, query string specifying genus must end up somewhere in the middle of the string // that is baseSearchUri. // chart.options.onClick.baseSearchUri must be defined in the type of chart (StatusChart, CategoryChart) // that is passed to the createDonutChart or createBarChart functions because cannot directly // make changes to the param baseSearchUri in updateChart(). if (chart.options.onClick.baseSearchUri) { navigate(`${chart.options.onClick.baseSearchUri}&status=${globals.encodedURIComponent(term)}&replication_type=${item}`); } else { navigate(`${baseSearchUri}&status=${globals.encodedURIComponent(term)}&replication_type=${item}`); } } }, }, }); document.getElementById(`${chartId}-legend`).innerHTML = chart.generateLegend(); resolve(chart); }, 'chartjs'); }); }
JavaScript
updateChart(chart, facetData) { const { award, linkUri, objectQuery } = this.props; // Extract the non-zero values, and corresponding labels and colors for the data. const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => labColorList[i % labColorList.length]); // Update chart data and redraw with the new data chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `${linkUri}${award.name}${objectQuery}&lab.title=`; chart.update(); // Redraw the updated legend document.getElementById(`${labChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
updateChart(chart, facetData) { const { award, linkUri, objectQuery } = this.props; // Extract the non-zero values, and corresponding labels and colors for the data. const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => labColorList[i % labColorList.length]); // Update chart data and redraw with the new data chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `${linkUri}${award.name}${objectQuery}&lab.title=`; chart.update(); // Redraw the updated legend document.getElementById(`${labChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
JavaScript
updateChart(chart, facetData) { const { award, linkUri, objectQuery, categoryFacet } = this.props; // Extract the non-zero values, and corresponding labels and colors for the data. const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => typeSpecificColorList[i % typeSpecificColorList.length]); // Update chart data and redraw with the new data. chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `${linkUri}${award.name}${objectQuery}&${categoryFacet}=`; chart.update(); // Redraw the updated legend document.getElementById(`${categoryChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
updateChart(chart, facetData) { const { award, linkUri, objectQuery, categoryFacet } = this.props; // Extract the non-zero values, and corresponding labels and colors for the data. const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => typeSpecificColorList[i % typeSpecificColorList.length]); // Update chart data and redraw with the new data. chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `${linkUri}${award.name}${objectQuery}&${categoryFacet}=`; chart.update(); // Redraw the updated legend document.getElementById(`${categoryChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
JavaScript
updateChart(chart, facetData) { // Extract the non-zero values, and corresponding labels and colors for the data. const { award } = this.props; const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => typeSpecificColorList[i % typeSpecificColorList.length]); const AntibodyQuery = generateQuery(this.props.selectedOrganisms, 'targets.organism.scientific_name='); // Update chart data and redraw with the new data. chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `/report/?type=AntibodyLot&award=/awards/${award.name}/${AntibodyQuery}&lot_reviews.status=`; chart.update(); // Redraw the updated legend document.getElementById(`${categoryChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
updateChart(chart, facetData) { // Extract the non-zero values, and corresponding labels and colors for the data. const { award } = this.props; const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => typeSpecificColorList[i % typeSpecificColorList.length]); const AntibodyQuery = generateQuery(this.props.selectedOrganisms, 'targets.organism.scientific_name='); // Update chart data and redraw with the new data. chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `/report/?type=AntibodyLot&award=/awards/${award.name}/${AntibodyQuery}&lot_reviews.status=`; chart.update(); // Redraw the updated legend document.getElementById(`${categoryChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
JavaScript
updateChart(chart, facetData) { const { award } = this.props; // Extract the non-zero values, and corresponding labels and colors for the data. const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => typeSpecificColorList[i % typeSpecificColorList.length]); // if (this.props.selectedOrganisms.length) const BiosampleQuery = generateQuery(this.props.selectedOrganisms, 'organism.scientific_name='); // Update chart data and redraw with the new data. chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `/report/?type=Biosample&award.name=${award.name}&${BiosampleQuery}&biosample_type=`; chart.update(); // Redraw the updated legend document.getElementById(`${categoryChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
updateChart(chart, facetData) { const { award } = this.props; // Extract the non-zero values, and corresponding labels and colors for the data. const values = []; const labels = []; facetData.forEach((item) => { if (item.doc_count) { values.push(item.doc_count); labels.push(item.key); } }); const colors = labels.map((label, i) => typeSpecificColorList[i % typeSpecificColorList.length]); // if (this.props.selectedOrganisms.length) const BiosampleQuery = generateQuery(this.props.selectedOrganisms, 'organism.scientific_name='); // Update chart data and redraw with the new data. chart.data.datasets[0].data = values; chart.data.datasets[0].backgroundColor = colors; chart.data.labels = labels; chart.options.onClick.baseSearchUri = `/report/?type=Biosample&award.name=${award.name}&${BiosampleQuery}&biosample_type=`; chart.update(); // Redraw the updated legend document.getElementById(`${categoryChartId}-${this.props.ident}-legend`).innerHTML = chart.generateLegend(); }
JavaScript
function StatusData(experiments, unreplicated, isogenic, anisogenic) { let unreplicatedArray; let isogenicArray; let anisogenicArray; const unreplicatedLabel = []; let unreplicatedDataset = []; const isogenicLabel = []; let isogenicDataset = []; const anisogenicLabel = []; let anisogenicDataset = []; // Find status in facets for each replicate type (unreplicated, isogenic, anisogenic) search if (experiments && experiments.facets && experiments.facets.length) { const unreplicatedFacet = unreplicated.facets.find(facet => facet.field === 'status'); const isogenicFacet = isogenic.facets.find(facet => facet.field === 'status'); const anisogenicFacet = anisogenic.facets.find(facet => facet.field === 'status'); unreplicatedArray = (unreplicatedFacet && unreplicatedFacet.terms && unreplicatedFacet.terms.length) ? unreplicatedFacet.terms : []; isogenicArray = (isogenicFacet && isogenicFacet.terms && isogenicFacet.terms.length) ? isogenicFacet.terms : []; anisogenicArray = (anisogenicFacet && anisogenicFacet.terms && anisogenicFacet.terms.length) ? anisogenicFacet.terms : []; } const labels = ['started', 'submitted', 'released', 'deleted', 'replaced', 'archived', 'revoked']; // Check existence of data for each of the keys in array labels // Ensures that for each replicate type there exists the same set of labels and the corresponding data values (in order) // so that it can be easily and accurately passed to chart.js in createBarChart // First pushes anything that has a key in labels, then sorts the dataset // If the array has no length, just push an array with 0 values if (unreplicatedArray.length) { for (let j = 0; j < labels.length; j += 1) { for (let i = 0; i < unreplicatedArray.length; i += 1) { if (unreplicatedArray[i].key === labels[j]) { unreplicatedLabel.push(unreplicatedArray[i].key); unreplicatedDataset.push(unreplicatedArray[i].doc_count); } } } for (let j = 0; j < labels.length; j += 1) { if (labels[j] !== unreplicatedLabel[j]) { unreplicatedLabel.splice(j, 0, labels[j]); unreplicatedDataset.splice(j, 0, 0); } } } else { unreplicatedDataset = [0, 0, 0, 0, 0, 0, 0, 0]; } if (isogenicArray.length) { for (let j = 0; j < labels.length; j += 1) { for (let i = 0; i < isogenicArray.length; i += 1) { if (isogenicArray[i].key === labels[j]) { isogenicLabel.push(isogenicArray[i].key); isogenicDataset.push(isogenicArray[i].doc_count); } } } for (let j = 0; j < labels.length; j += 1) { if (labels[j] !== isogenicLabel[j]) { isogenicLabel.splice(j, 0, labels[j]); isogenicDataset.splice(j, 0, 0); } } } else { isogenicDataset = [0, 0, 0, 0, 0, 0, 0, 0]; } if (anisogenicArray.length) { for (let j = 0; j < labels.length; j += 1) { for (let i = 0; i < anisogenicArray.length; i += 1) { if (anisogenicArray[i].key === labels[j]) { anisogenicLabel.push(anisogenicArray[i].key); anisogenicDataset.push(anisogenicArray[i].doc_count); } } } for (let j = 0; j < labels.length; j += 1) { if (labels[j] !== anisogenicLabel[j]) { anisogenicLabel.splice(j, 0, labels[j]); anisogenicDataset.splice(j, 0, 0); } } } else { anisogenicDataset = [0, 0, 0, 0, 0, 0, 0, 0]; } return ({ labels, unreplicatedDataset, isogenicDataset, anisogenicDataset }); }
function StatusData(experiments, unreplicated, isogenic, anisogenic) { let unreplicatedArray; let isogenicArray; let anisogenicArray; const unreplicatedLabel = []; let unreplicatedDataset = []; const isogenicLabel = []; let isogenicDataset = []; const anisogenicLabel = []; let anisogenicDataset = []; // Find status in facets for each replicate type (unreplicated, isogenic, anisogenic) search if (experiments && experiments.facets && experiments.facets.length) { const unreplicatedFacet = unreplicated.facets.find(facet => facet.field === 'status'); const isogenicFacet = isogenic.facets.find(facet => facet.field === 'status'); const anisogenicFacet = anisogenic.facets.find(facet => facet.field === 'status'); unreplicatedArray = (unreplicatedFacet && unreplicatedFacet.terms && unreplicatedFacet.terms.length) ? unreplicatedFacet.terms : []; isogenicArray = (isogenicFacet && isogenicFacet.terms && isogenicFacet.terms.length) ? isogenicFacet.terms : []; anisogenicArray = (anisogenicFacet && anisogenicFacet.terms && anisogenicFacet.terms.length) ? anisogenicFacet.terms : []; } const labels = ['started', 'submitted', 'released', 'deleted', 'replaced', 'archived', 'revoked']; // Check existence of data for each of the keys in array labels // Ensures that for each replicate type there exists the same set of labels and the corresponding data values (in order) // so that it can be easily and accurately passed to chart.js in createBarChart // First pushes anything that has a key in labels, then sorts the dataset // If the array has no length, just push an array with 0 values if (unreplicatedArray.length) { for (let j = 0; j < labels.length; j += 1) { for (let i = 0; i < unreplicatedArray.length; i += 1) { if (unreplicatedArray[i].key === labels[j]) { unreplicatedLabel.push(unreplicatedArray[i].key); unreplicatedDataset.push(unreplicatedArray[i].doc_count); } } } for (let j = 0; j < labels.length; j += 1) { if (labels[j] !== unreplicatedLabel[j]) { unreplicatedLabel.splice(j, 0, labels[j]); unreplicatedDataset.splice(j, 0, 0); } } } else { unreplicatedDataset = [0, 0, 0, 0, 0, 0, 0, 0]; } if (isogenicArray.length) { for (let j = 0; j < labels.length; j += 1) { for (let i = 0; i < isogenicArray.length; i += 1) { if (isogenicArray[i].key === labels[j]) { isogenicLabel.push(isogenicArray[i].key); isogenicDataset.push(isogenicArray[i].doc_count); } } } for (let j = 0; j < labels.length; j += 1) { if (labels[j] !== isogenicLabel[j]) { isogenicLabel.splice(j, 0, labels[j]); isogenicDataset.splice(j, 0, 0); } } } else { isogenicDataset = [0, 0, 0, 0, 0, 0, 0, 0]; } if (anisogenicArray.length) { for (let j = 0; j < labels.length; j += 1) { for (let i = 0; i < anisogenicArray.length; i += 1) { if (anisogenicArray[i].key === labels[j]) { anisogenicLabel.push(anisogenicArray[i].key); anisogenicDataset.push(anisogenicArray[i].doc_count); } } } for (let j = 0; j < labels.length; j += 1) { if (labels[j] !== anisogenicLabel[j]) { anisogenicLabel.splice(j, 0, labels[j]); anisogenicDataset.splice(j, 0, 0); } } } else { anisogenicDataset = [0, 0, 0, 0, 0, 0, 0, 0]; } return ({ labels, unreplicatedDataset, isogenicDataset, anisogenicDataset }); }
JavaScript
function generateUpdatedSpeciesArray(categories, query, updatedSpeciesArray) { let categorySpeciesArray; if (categories && categories.facets && categories.facets.length) { const genusFacet = categories.facets.find(facet => facet.field === query); categorySpeciesArray = (genusFacet && genusFacet.terms && genusFacet.terms.length) ? genusFacet.terms : []; const categorySpeciesArrayLength = categorySpeciesArray.length; for (let j = 0; j < categorySpeciesArrayLength; j += 1) { if (categorySpeciesArray[j].doc_count !== 0) { updatedSpeciesArray.push(categorySpeciesArray[j].key); } } } return updatedSpeciesArray; }
function generateUpdatedSpeciesArray(categories, query, updatedSpeciesArray) { let categorySpeciesArray; if (categories && categories.facets && categories.facets.length) { const genusFacet = categories.facets.find(facet => facet.field === query); categorySpeciesArray = (genusFacet && genusFacet.terms && genusFacet.terms.length) ? genusFacet.terms : []; const categorySpeciesArrayLength = categorySpeciesArray.length; for (let j = 0; j < categorySpeciesArrayLength; j += 1) { if (categorySpeciesArray[j].doc_count !== 0) { updatedSpeciesArray.push(categorySpeciesArray[j].key); } } } return updatedSpeciesArray; }
JavaScript
function sortTerms(dateArray) { // Use Moment to format arrays of submitted and released date const standardTerms = dateArray.map((term) => { const standardDate = moment(term.key, ['MMMM, YYYY', 'YYYY-MM']).format('YYYY-MM'); return { key: standardDate, doc_count: term.doc_count }; }); // Sort arrays chronologically const sortedTerms = standardTerms.sort((termA, termB) => { if (termA.key < termB.key) { return -1; } else if (termB.key < termA.key) { return 1; } return 0; }); return ( sortedTerms ); }
function sortTerms(dateArray) { // Use Moment to format arrays of submitted and released date const standardTerms = dateArray.map((term) => { const standardDate = moment(term.key, ['MMMM, YYYY', 'YYYY-MM']).format('YYYY-MM'); return { key: standardDate, doc_count: term.doc_count }; }); // Sort arrays chronologically const sortedTerms = standardTerms.sort((termA, termB) => { if (termA.key < termB.key) { return -1; } else if (termB.key < termA.key) { return 1; } return 0; }); return ( sortedTerms ); }
JavaScript
function fileAuditStatus(file) { let highestAuditLevel; if (file.audit) { const sortedAuditLevels = _(Object.keys(file.audit)).sortBy(level => -file.audit[level][0].level); highestAuditLevel = sortedAuditLevels[0]; } else { highestAuditLevel = 'OK'; } return <AuditIcon level={highestAuditLevel} addClasses="file-audit-status" />; }
function fileAuditStatus(file) { let highestAuditLevel; if (file.audit) { const sortedAuditLevels = _(Object.keys(file.audit)).sortBy(level => -file.audit[level][0].level); highestAuditLevel = sortedAuditLevels[0]; } else { highestAuditLevel = 'OK'; } return <AuditIcon level={highestAuditLevel} addClasses="file-audit-status" />; }
JavaScript
function fileAccessionSort(a, b) { if (!a.accession !== !b.accession) { // One or the other but not both use an external accession. Sort so regular accession // comes first. return a.accession ? -1 : 1; } // We either have two accessions or two external accessions. Do a case-insensitive compare on // the calculated property that gets external_accession if accession isn't available. const aTitle = a.title.toLowerCase(); const bTitle = b.title.toLowerCase(); return aTitle > bTitle ? 1 : (aTitle < bTitle ? -1 : 0); }
function fileAccessionSort(a, b) { if (!a.accession !== !b.accession) { // One or the other but not both use an external accession. Sort so regular accession // comes first. return a.accession ? -1 : 1; } // We either have two accessions or two external accessions. Do a case-insensitive compare on // the calculated property that gets external_accession if accession isn't available. const aTitle = a.title.toLowerCase(); const bTitle = b.title.toLowerCase(); return aTitle > bTitle ? 1 : (aTitle < bTitle ? -1 : 0); }
JavaScript
function collectAssembliesAnnotations(files) { let filterOptions = []; // Get the assembly and annotation of each file. Assembly is required to be included in the list files.forEach((file) => { if (file.output_category !== 'raw data' && file.assembly) { filterOptions.push({ assembly: file.assembly, annotation: file.genome_annotation }); } }); // Eliminate duplicate entries in filterOptions. Duplicates are detected by combining the // assembly and annotation into a long string. Use the '!' separator so that highly unlikely // anomalies don't pass undetected (e.g. hg19!V19 and hg1!9V19 -- again, highly unlikely). filterOptions = filterOptions.length ? _(filterOptions).uniq(option => `${option.assembly}!${option.annotation ? option.annotation : ''}`) : []; // Now begin a two-stage sort, with the primary key being the assembly in a specific priority // order specified by the assemblyPriority array, and the secondary key being the annotation // in which we attempt to suss out the ordering from the way it looks, highest-numbered first. // First, sort by annotation and reverse the sort at the end. filterOptions = _(filterOptions).sortBy((option) => { if (option.annotation) { // Extract any number from the annotation. const annotationMatch = option.annotation.match(/^[A-Z]+(\d+).*$/); if (annotationMatch) { // Return the number to the sorting algoritm. return Number(annotationMatch[1]); } } // No annotation gets sorted to the top. return null; }).reverse(); // Now sort by assembly priority order as the primary sorting key. assemblyPriority is a global // array. return _(filterOptions).sortBy(option => _(globals.assemblyPriority).indexOf(option.assembly)); }
function collectAssembliesAnnotations(files) { let filterOptions = []; // Get the assembly and annotation of each file. Assembly is required to be included in the list files.forEach((file) => { if (file.output_category !== 'raw data' && file.assembly) { filterOptions.push({ assembly: file.assembly, annotation: file.genome_annotation }); } }); // Eliminate duplicate entries in filterOptions. Duplicates are detected by combining the // assembly and annotation into a long string. Use the '!' separator so that highly unlikely // anomalies don't pass undetected (e.g. hg19!V19 and hg1!9V19 -- again, highly unlikely). filterOptions = filterOptions.length ? _(filterOptions).uniq(option => `${option.assembly}!${option.annotation ? option.annotation : ''}`) : []; // Now begin a two-stage sort, with the primary key being the assembly in a specific priority // order specified by the assemblyPriority array, and the secondary key being the annotation // in which we attempt to suss out the ordering from the way it looks, highest-numbered first. // First, sort by annotation and reverse the sort at the end. filterOptions = _(filterOptions).sortBy((option) => { if (option.annotation) { // Extract any number from the annotation. const annotationMatch = option.annotation.match(/^[A-Z]+(\d+).*$/); if (annotationMatch) { // Return the number to the sorting algoritm. return Number(annotationMatch[1]); } } // No annotation gets sorted to the top. return null; }).reverse(); // Now sort by assembly priority order as the primary sorting key. assemblyPriority is a global // array. return _(filterOptions).sortBy(option => _(globals.assemblyPriority).indexOf(option.assembly)); }
JavaScript
function qcAbbr(qc) { // As we add more QC object types, add to this object. const qcAbbrMap = { BigwigcorrelateQualityMetric: 'BC', BismarkQualityMetric: 'BK', ChipSeqFilterQualityMetric: 'CF', ComplexityXcorrQualityMetric: 'CX', CorrelationQualityMetric: 'CN', CpgCorrelationQualityMetric: 'CC', DuplicatesQualityMetric: 'DS', EdwbamstatsQualityMetric: 'EB', EdwcomparepeaksQualityMetric: 'EP', Encode2ChipSeqQualityMetric: 'EC', FilteringQualityMetric: 'FG', GenericQualityMetric: 'GN', HotspotQualityMetric: 'HS', IDRQualityMetric: 'ID', IdrSummaryQualityMetric: 'IS', MadQualityMetric: 'MD', SamtoolsFlagstatsQualityMetric: 'SF', SamtoolsStatsQualityMetric: 'SS', StarQualityMetric: 'SR', TrimmingQualityMetric: 'TG', }; let abbr = qcAbbrMap[qc['@type'][0]]; if (!abbr) { // 'QC' is the generic, unmatched abbreviation if qcAbbrMap doesn't have a match. abbr = 'QC'; } return abbr; }
function qcAbbr(qc) { // As we add more QC object types, add to this object. const qcAbbrMap = { BigwigcorrelateQualityMetric: 'BC', BismarkQualityMetric: 'BK', ChipSeqFilterQualityMetric: 'CF', ComplexityXcorrQualityMetric: 'CX', CorrelationQualityMetric: 'CN', CpgCorrelationQualityMetric: 'CC', DuplicatesQualityMetric: 'DS', EdwbamstatsQualityMetric: 'EB', EdwcomparepeaksQualityMetric: 'EP', Encode2ChipSeqQualityMetric: 'EC', FilteringQualityMetric: 'FG', GenericQualityMetric: 'GN', HotspotQualityMetric: 'HS', IDRQualityMetric: 'ID', IdrSummaryQualityMetric: 'IS', MadQualityMetric: 'MD', SamtoolsFlagstatsQualityMetric: 'SF', SamtoolsStatsQualityMetric: 'SS', StarQualityMetric: 'SR', TrimmingQualityMetric: 'TG', }; let abbr = qcAbbrMap[qc['@type'][0]]; if (!abbr) { // 'QC' is the generic, unmatched abbreviation if qcAbbrMap doesn't have a match. abbr = 'QC'; } return abbr; }
JavaScript
function collectDerivedFroms(file, fileDataset, selectedAssembly, selectedAnnotation, allFiles) { let accumulatedDerivedFroms = {}; // Only step up the chain of derived froms if the file has one. Otherwise we're at a terminal // file of this derived_from branch and can start stepping back down the chain. We also stop // going up the chain once we get to a file not in the current dataset, which might be a // processed file that doesn't belong in the graph, or a contributing file. Note that we have a // risk of infinite recursion if the file data incluees a derived_from loop, which isn't valid. if (file.derived_from && file.derived_from.length && file.dataset === fileDataset['@id']) { // File is the product of at least one derived_from chain, so for any files this file // derives from (parent files), go up the chain continuing to collect the files involved // in the current branch of the chain. for (let i = 0; i < file.derived_from.length; i += 1) { const derivedFileAtId = file.derived_from[i]; // derived_from doesn't currently embed files; it's just a list of file @ids, and we // have to use `allFiles` to get the corresponding file objects. const derivedFile = allFiles[derivedFileAtId]; if (!derivedFile || isCompatibleAssemblyAnnotation(derivedFile, selectedAssembly, selectedAnnotation)) { // The derived_from file either has an assembly/annotation compatible with the // currently selected ones (including raw files that don't have an assembly nor // annotation) -- OR we have the @id of a derived_from file not in this dataset and // so doesn't exist in `allFiles`, which indicates a contributing file. let branchDerivedFroms; if (derivedFile) { // The derived_from file exists in the current dataset, so use that as the new // root of the derived_from chain to recursively go up the chain. branchDerivedFroms = collectDerivedFroms(derivedFile, fileDataset, selectedAssembly, selectedAnnotation, allFiles); } else { // The derived_from file does not exist in the current dataset, so this is a // terminal file that gets a clean entry to return to the lower level of the // chain. accumulatedDerivedFroms[derivedFileAtId] = null; branchDerivedFroms = accumulatedDerivedFroms; } // branchDerivedFroms keys with null values indicate files that are the direct // parent of `file`. Replace the null value with `file` itself. const branchDerivedFromAtIds = Object.keys(branchDerivedFroms); for (let j = 0; j < branchDerivedFromAtIds.length; j += 1) { const oneDerivedFromAtId = branchDerivedFromAtIds[j]; if (branchDerivedFroms[oneDerivedFromAtId] === null) { branchDerivedFroms[oneDerivedFromAtId] = file; } } // Add the current file object to the object that accumulates all the files this // file derives from. accumulatedDerivedFroms = Object.assign(accumulatedDerivedFroms, branchDerivedFroms); } } } // Else the file has no derived_from chain or has a conflicting dataset, and we can stop going // up the chain of derived froms. // Now add a property to the object of collected derived_froms keyed by the file's @id and // containing an null to be filled in by child files. accumulatedDerivedFroms[file['@id']] = null; return accumulatedDerivedFroms; }
function collectDerivedFroms(file, fileDataset, selectedAssembly, selectedAnnotation, allFiles) { let accumulatedDerivedFroms = {}; // Only step up the chain of derived froms if the file has one. Otherwise we're at a terminal // file of this derived_from branch and can start stepping back down the chain. We also stop // going up the chain once we get to a file not in the current dataset, which might be a // processed file that doesn't belong in the graph, or a contributing file. Note that we have a // risk of infinite recursion if the file data incluees a derived_from loop, which isn't valid. if (file.derived_from && file.derived_from.length && file.dataset === fileDataset['@id']) { // File is the product of at least one derived_from chain, so for any files this file // derives from (parent files), go up the chain continuing to collect the files involved // in the current branch of the chain. for (let i = 0; i < file.derived_from.length; i += 1) { const derivedFileAtId = file.derived_from[i]; // derived_from doesn't currently embed files; it's just a list of file @ids, and we // have to use `allFiles` to get the corresponding file objects. const derivedFile = allFiles[derivedFileAtId]; if (!derivedFile || isCompatibleAssemblyAnnotation(derivedFile, selectedAssembly, selectedAnnotation)) { // The derived_from file either has an assembly/annotation compatible with the // currently selected ones (including raw files that don't have an assembly nor // annotation) -- OR we have the @id of a derived_from file not in this dataset and // so doesn't exist in `allFiles`, which indicates a contributing file. let branchDerivedFroms; if (derivedFile) { // The derived_from file exists in the current dataset, so use that as the new // root of the derived_from chain to recursively go up the chain. branchDerivedFroms = collectDerivedFroms(derivedFile, fileDataset, selectedAssembly, selectedAnnotation, allFiles); } else { // The derived_from file does not exist in the current dataset, so this is a // terminal file that gets a clean entry to return to the lower level of the // chain. accumulatedDerivedFroms[derivedFileAtId] = null; branchDerivedFroms = accumulatedDerivedFroms; } // branchDerivedFroms keys with null values indicate files that are the direct // parent of `file`. Replace the null value with `file` itself. const branchDerivedFromAtIds = Object.keys(branchDerivedFroms); for (let j = 0; j < branchDerivedFromAtIds.length; j += 1) { const oneDerivedFromAtId = branchDerivedFromAtIds[j]; if (branchDerivedFroms[oneDerivedFromAtId] === null) { branchDerivedFroms[oneDerivedFromAtId] = file; } } // Add the current file object to the object that accumulates all the files this // file derives from. accumulatedDerivedFroms = Object.assign(accumulatedDerivedFroms, branchDerivedFroms); } } } // Else the file has no derived_from chain or has a conflicting dataset, and we can stop going // up the chain of derived froms. // Now add a property to the object of collected derived_froms keyed by the file's @id and // containing an null to be filled in by child files. accumulatedDerivedFroms[file['@id']] = null; return accumulatedDerivedFroms; }
JavaScript
function rDerivedFileIds(file) { if (file.derived_from && file.derived_from.length) { return file.derived_from.sort().join(); } return ''; }
function rDerivedFileIds(file) { if (file.derived_from && file.derived_from.length) { return file.derived_from.sort().join(); } return ''; }
JavaScript
function fileCssClassGen(file, active, colorizeNode, addClasses) { let statusClass; if (colorizeNode) { statusClass = file.status.replace(/ /g, '-'); } return `pipeline-node-file${active ? ' active' : ''}${colorizeNode ? ` ${statusClass}` : ''}${addClasses ? ` ${addClasses}` : ''}`; }
function fileCssClassGen(file, active, colorizeNode, addClasses) { let statusClass; if (colorizeNode) { statusClass = file.status.replace(/ /g, '-'); } return `pipeline-node-file${active ? ' active' : ''}${colorizeNode ? ` ${statusClass}` : ''}${addClasses ? ` ${addClasses}` : ''}`; }
JavaScript
componentDidMount() { if (!this.props.altFilterDefault) { this.setFilter('0'); } }
componentDidMount() { if (!this.props.altFilterDefault) { this.setFilter('0'); } }
JavaScript
function qcModalContent(qc, file, qcSchema, genericQCSchema) { let qcPanels = []; // Each QC metric panel to display let filesOfMetric = []; // Array of accessions of files that share this metric // Make an array of the accessions of files that share this quality metrics object. // quality_metric_of is an array of @ids because they're not embedded, and we're trying // to avoid embedding where not absolutely needed. So use a regex to extract the files' // accessions from the @ids. After generating the array, filter out empty entries. if (qc.quality_metric_of && qc.quality_metric_of.length) { filesOfMetric = qc.quality_metric_of.map((metricId) => { // Extract the file's accession from the @id const match = globals.atIdToAccession(metricId); // Return matches that *don't* match the file whose QC node we've clicked if (match !== file.title) { return match; } return ''; }).filter(acc => !!acc); } // Get the list of attachment properties for the given qc object @type. and generate the JSX for their display panels. // The list of keys for attachment properties to display comes from qcAttachmentProperties. Use the @type for the attachment // property as a key to retrieve the list of properties appropriate for that QC type. const qcAttachmentPropertyList = qcAttachmentProperties[qc['@type'][0]]; if (qcAttachmentPropertyList) { qcPanels = _(qcAttachmentPropertyList.map((attachmentPropertyInfo) => { // Each object in the list has only one key (the metric attachment property name), so get it here. const attachmentPropertyName = Object.keys(attachmentPropertyInfo)[0]; const attachment = qc[attachmentPropertyName]; // Generate the JSX for the panel. Use the property name as the key to get the corresponding human-readable description for the title if (attachment) { return ( <AttachmentPanel key={attachmentPropertyName} context={qc} attachment={qc[attachmentPropertyName]} title={attachmentPropertyInfo[attachmentPropertyName]} modal /> ); } return null; })).compact(); } // Convert the QC metric object @id to a displayable string let qcName = qc['@id'].match(/^\/([a-z0-9-]*)\/.*$/i); if (qcName && qcName[1]) { qcName = qcName[1].replace(/-/g, ' '); qcName = qcName[0].toUpperCase() + qcName.substring(1); } const header = ( <div className="details-view-info"> <h4>{qcName} of {file.title}</h4> {filesOfMetric.length ? <h5>Shared with {filesOfMetric.join(', ')}</h5> : null} </div> ); const body = ( <div> <div className="row"> <div className="col-md-4 col-sm-6 col-xs-12"> <QCDataDisplay qcMetric={qc} qcSchema={qcSchema} genericQCSchema={genericQCSchema} /> </div> {(qcPanels && qcPanels.length) || qc.attachment ? <div className="col-md-8 col-sm-12 quality-metrics-attachments"> <div className="row"> <h5>Quality metric attachments</h5> <div className="flexrow attachment-panel-inner"> {/* If the metrics object has an `attachment` property, display that first, then display the properties not named `attachment` but which have their own schema attribute, `attachment`, set to true */} {qc.attachment ? <AttachmentPanel context={qc} attachment={qc.attachment} title="Attachment" modal /> : null} {qcPanels} </div> </div> </div> : null} </div> </div> ); return { header, body }; }
function qcModalContent(qc, file, qcSchema, genericQCSchema) { let qcPanels = []; // Each QC metric panel to display let filesOfMetric = []; // Array of accessions of files that share this metric // Make an array of the accessions of files that share this quality metrics object. // quality_metric_of is an array of @ids because they're not embedded, and we're trying // to avoid embedding where not absolutely needed. So use a regex to extract the files' // accessions from the @ids. After generating the array, filter out empty entries. if (qc.quality_metric_of && qc.quality_metric_of.length) { filesOfMetric = qc.quality_metric_of.map((metricId) => { // Extract the file's accession from the @id const match = globals.atIdToAccession(metricId); // Return matches that *don't* match the file whose QC node we've clicked if (match !== file.title) { return match; } return ''; }).filter(acc => !!acc); } // Get the list of attachment properties for the given qc object @type. and generate the JSX for their display panels. // The list of keys for attachment properties to display comes from qcAttachmentProperties. Use the @type for the attachment // property as a key to retrieve the list of properties appropriate for that QC type. const qcAttachmentPropertyList = qcAttachmentProperties[qc['@type'][0]]; if (qcAttachmentPropertyList) { qcPanels = _(qcAttachmentPropertyList.map((attachmentPropertyInfo) => { // Each object in the list has only one key (the metric attachment property name), so get it here. const attachmentPropertyName = Object.keys(attachmentPropertyInfo)[0]; const attachment = qc[attachmentPropertyName]; // Generate the JSX for the panel. Use the property name as the key to get the corresponding human-readable description for the title if (attachment) { return ( <AttachmentPanel key={attachmentPropertyName} context={qc} attachment={qc[attachmentPropertyName]} title={attachmentPropertyInfo[attachmentPropertyName]} modal /> ); } return null; })).compact(); } // Convert the QC metric object @id to a displayable string let qcName = qc['@id'].match(/^\/([a-z0-9-]*)\/.*$/i); if (qcName && qcName[1]) { qcName = qcName[1].replace(/-/g, ' '); qcName = qcName[0].toUpperCase() + qcName.substring(1); } const header = ( <div className="details-view-info"> <h4>{qcName} of {file.title}</h4> {filesOfMetric.length ? <h5>Shared with {filesOfMetric.join(', ')}</h5> : null} </div> ); const body = ( <div> <div className="row"> <div className="col-md-4 col-sm-6 col-xs-12"> <QCDataDisplay qcMetric={qc} qcSchema={qcSchema} genericQCSchema={genericQCSchema} /> </div> {(qcPanels && qcPanels.length) || qc.attachment ? <div className="col-md-8 col-sm-12 quality-metrics-attachments"> <div className="row"> <h5>Quality metric attachments</h5> <div className="flexrow attachment-panel-inner"> {/* If the metrics object has an `attachment` property, display that first, then display the properties not named `attachment` but which have their own schema attribute, `attachment`, set to true */} {qc.attachment ? <AttachmentPanel context={qc} attachment={qc.attachment} title="Attachment" modal /> : null} {qcPanels} </div> </div> </div> : null} </div> </div> ); return { header, body }; }
JavaScript
function auditsDisplayed(audits, session) { const loggedIn = !!(session && session['auth.userid']); return (audits && Object.keys(audits).length) && (loggedIn || !(Object.keys(audits).length === 1 && audits.INTERNAL_ACTION)); }
function auditsDisplayed(audits, session) { const loggedIn = !!(session && session['auth.userid']); return (audits && Object.keys(audits).length) && (loggedIn || !(Object.keys(audits).length === 1 && audits.INTERNAL_ACTION)); }
JavaScript
addEdge(source, target) { const newEdge = {}; newEdge.id = ''; newEdge.source = source; newEdge.target = target; this.edges.push(newEdge); }
addEdge(source, target) { const newEdge = {}; newEdge.id = ''; newEdge.source = source; newEdge.target = target; this.edges.push(newEdge); }
JavaScript
map(fn, context, nodes) { const thisNodes = nodes || this.nodes; let returnArray = []; for (let i = 0; i < thisNodes.length; i += 1) { const node = thisNodes[i]; // Call the given function and add its return value to the array we're collecting returnArray.push(fn.call(context, node)); // If the node has its own nodes, recurse if (node.nodes && node.nodes.length) { returnArray = returnArray.concat(this.map(fn, context, node.nodes)); } } return returnArray; }
map(fn, context, nodes) { const thisNodes = nodes || this.nodes; let returnArray = []; for (let i = 0; i < thisNodes.length; i += 1) { const node = thisNodes[i]; // Call the given function and add its return value to the array we're collecting returnArray.push(fn.call(context, node)); // If the node has its own nodes, recurse if (node.nodes && node.nodes.length) { returnArray = returnArray.concat(this.map(fn, context, node.nodes)); } } return returnArray; }
JavaScript
static convertGraph(jsonGraph, graph) { // graph: dagre graph object // parent: JsonGraph node to insert nodes into function convertGraphInner(subgraph, parent) { // For each node in parent node (or top-level graph) parent.nodes.forEach((node) => { subgraph.setNode(node.id, { label: node.label.length > 1 ? node.label : node.label[0], rx: node.metadata.cornerRadius, ry: node.metadata.cornerRadius, class: node.metadata.cssClass, shape: node.metadata.shape, paddingLeft: '20', paddingRight: '20', paddingTop: '10', paddingBottom: '10', subnodes: node.subnodes, }); if (!parent.root) { subgraph.setParent(node.id, parent.id); } if (node.nodes.length) { convertGraphInner(subgraph, node); } }); } // Convert the nodes convertGraphInner(graph, jsonGraph); // Convert the edges jsonGraph.edges.forEach((edge) => { graph.setEdge(edge.source, edge.target, { lineInterpolate: 'basis' }); }); }
static convertGraph(jsonGraph, graph) { // graph: dagre graph object // parent: JsonGraph node to insert nodes into function convertGraphInner(subgraph, parent) { // For each node in parent node (or top-level graph) parent.nodes.forEach((node) => { subgraph.setNode(node.id, { label: node.label.length > 1 ? node.label : node.label[0], rx: node.metadata.cornerRadius, ry: node.metadata.cornerRadius, class: node.metadata.cssClass, shape: node.metadata.shape, paddingLeft: '20', paddingRight: '20', paddingTop: '10', paddingBottom: '10', subnodes: node.subnodes, }); if (!parent.root) { subgraph.setParent(node.id, parent.id); } if (node.nodes.length) { convertGraphInner(subgraph, node); } }); } // Convert the nodes convertGraphInner(graph, jsonGraph); // Convert the edges jsonGraph.edges.forEach((edge) => { graph.setEdge(edge.source, edge.target, { lineInterpolate: 'basis' }); }); }
JavaScript
function convertGraphInner(subgraph, parent) { // For each node in parent node (or top-level graph) parent.nodes.forEach((node) => { subgraph.setNode(node.id, { label: node.label.length > 1 ? node.label : node.label[0], rx: node.metadata.cornerRadius, ry: node.metadata.cornerRadius, class: node.metadata.cssClass, shape: node.metadata.shape, paddingLeft: '20', paddingRight: '20', paddingTop: '10', paddingBottom: '10', subnodes: node.subnodes, }); if (!parent.root) { subgraph.setParent(node.id, parent.id); } if (node.nodes.length) { convertGraphInner(subgraph, node); } }); }
function convertGraphInner(subgraph, parent) { // For each node in parent node (or top-level graph) parent.nodes.forEach((node) => { subgraph.setNode(node.id, { label: node.label.length > 1 ? node.label : node.label[0], rx: node.metadata.cornerRadius, ry: node.metadata.cornerRadius, class: node.metadata.cssClass, shape: node.metadata.shape, paddingLeft: '20', paddingRight: '20', paddingTop: '10', paddingBottom: '10', subnodes: node.subnodes, }); if (!parent.root) { subgraph.setParent(node.id, parent.id); } if (node.nodes.length) { convertGraphInner(subgraph, node); } }); }
JavaScript
componentDidUpdate() { if (this.dagreD3 && !this.cv.zoomMouseDown) { const el = this.refs.graphdisplay; // Change in React 0.14 const { viewBoxWidth, viewBoxHeight } = this.drawGraph(el); // Bind node/subnode click handlers to parent component handlers this.bindClickHandlers(this.d3, el); // If the viewbox has changed since the last time, need to recalculate the zooming // parameters. if (Math.abs(viewBoxWidth - this.cv.viewBoxWidth) > 10 || Math.abs(viewBoxHeight - this.cv.viewBoxHeight) > 10) { // Based on the size of the graph and view box, set the initial zoom level to // something that fits well. const initialZoomLevel = this.setInitialZoomLevel(el, this.cv.savedSvg); this.setState({ zoomLevel: initialZoomLevel }); } this.cv.viewBoxWidth = viewBoxWidth; this.cv.viewBoxHeight = viewBoxHeight; } }
componentDidUpdate() { if (this.dagreD3 && !this.cv.zoomMouseDown) { const el = this.refs.graphdisplay; // Change in React 0.14 const { viewBoxWidth, viewBoxHeight } = this.drawGraph(el); // Bind node/subnode click handlers to parent component handlers this.bindClickHandlers(this.d3, el); // If the viewbox has changed since the last time, need to recalculate the zooming // parameters. if (Math.abs(viewBoxWidth - this.cv.viewBoxWidth) > 10 || Math.abs(viewBoxHeight - this.cv.viewBoxHeight) > 10) { // Based on the size of the graph and view box, set the initial zoom level to // something that fits well. const initialZoomLevel = this.setInitialZoomLevel(el, this.cv.savedSvg); this.setState({ zoomLevel: initialZoomLevel }); } this.cv.viewBoxWidth = viewBoxWidth; this.cv.viewBoxHeight = viewBoxHeight; } }
JavaScript
function attachStyles(el) { let stylesText = ''; const sheets = document.styleSheets; // Search every style in the style sheet(s) for those applying to graphs. // Note: Not using ES5 looping constructs because these aren’t real arrays. if (sheets) { for (let i = 0; i < sheets.length; i += 1) { const rules = sheets[i].cssRules; if (rules) { for (let j = 0; j < rules.length; j += 1) { const rule = rules[j]; // If a style rule starts with 'g.' (svg group), we know it applies to the graph. // Note: In some browsers, indexOf is a bit faster; on others substring is a bit faster. // FF(31)'s substring is much faster than indexOf. if (typeof (rule.style) !== 'undefined' && rule.selectorText && rule.selectorText.substring(0, 2) === 'g.') { // If any elements use this style, add the style's CSS text to our style text accumulator. const elems = el.querySelectorAll(rule.selectorText); if (elems.length) { stylesText += `${rule.selectorText} { ${rule.style.cssText} }\n`; } } } } } } // Insert the collected SVG styles into a new style element const styleEl = document.createElement('style'); styleEl.setAttribute('type', 'text/css'); styleEl.innerHTML = `/* <![CDATA[ */\n${stylesText}\n/* ]]> */`; // Insert the new style element into the beginning of the given SVG element el.insertBefore(styleEl, el.firstChild); }
function attachStyles(el) { let stylesText = ''; const sheets = document.styleSheets; // Search every style in the style sheet(s) for those applying to graphs. // Note: Not using ES5 looping constructs because these aren’t real arrays. if (sheets) { for (let i = 0; i < sheets.length; i += 1) { const rules = sheets[i].cssRules; if (rules) { for (let j = 0; j < rules.length; j += 1) { const rule = rules[j]; // If a style rule starts with 'g.' (svg group), we know it applies to the graph. // Note: In some browsers, indexOf is a bit faster; on others substring is a bit faster. // FF(31)'s substring is much faster than indexOf. if (typeof (rule.style) !== 'undefined' && rule.selectorText && rule.selectorText.substring(0, 2) === 'g.') { // If any elements use this style, add the style's CSS text to our style text accumulator. const elems = el.querySelectorAll(rule.selectorText); if (elems.length) { stylesText += `${rule.selectorText} { ${rule.style.cssText} }\n`; } } } } } } // Insert the collected SVG styles into a new style element const styleEl = document.createElement('style'); styleEl.setAttribute('type', 'text/css'); styleEl.innerHTML = `/* <![CDATA[ */\n${stylesText}\n/* ]]> */`; // Insert the new style element into the beginning of the given SVG element el.insertBefore(styleEl, el.firstChild); }
JavaScript
function responderSaludo(nombre, apellido, trabajo, esDev) { console.log(`-Buenos dias ${nombre} ${apellido}`) if(esDev) { console.log(`-Ah mira, no sabia que eras ${trabajo}`) } }
function responderSaludo(nombre, apellido, trabajo, esDev) { console.log(`-Buenos dias ${nombre} ${apellido}`) if(esDev) { console.log(`-Ah mira, no sabia que eras ${trabajo}`) } }
JavaScript
booleanize (val) { val = val == null ? false : val switch (typeof val) { case 'boolean': return val case 'string': switch (val) { case 'true': case 1: case '1': case 'on': case 'yes': case 'enable': return true case 'null': default: return false } case 'function': case 'object': return true default: return false } }
booleanize (val) { val = val == null ? false : val switch (typeof val) { case 'boolean': return val case 'string': switch (val) { case 'true': case 1: case '1': case 'on': case 'yes': case 'enable': return true case 'null': default: return false } case 'function': case 'object': return true default: return false } }
JavaScript
isSet (flag) { return this.config.combined[flag] ? this.config.combined[flag] : false }
isSet (flag) { return this.config.combined[flag] ? this.config.combined[flag] : false }
JavaScript
function checkTimeout() { var currentTime = new Date().getTime(); if ( currentTime > startTime + timeoutLength ) { clearInterval( interval ); logout(); } }
function checkTimeout() { var currentTime = new Date().getTime(); if ( currentTime > startTime + timeoutLength ) { clearInterval( interval ); logout(); } }
JavaScript
function Container({ children, className }) { return ( <div className={"container " + className}> {children} </div> ); }
function Container({ children, className }) { return ( <div className={"container " + className}> {children} </div> ); }
JavaScript
function RuntimeError(transactions, vmOutput) { // Why not just Error.apply(this, [message])? See // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.results = {}; this.hashes = []; // handles creating this.message this.combine(transactions, vmOutput); }
function RuntimeError(transactions, vmOutput) { // Why not just Error.apply(this, [message])? See // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.results = {}; this.hashes = []; // handles creating this.message this.combine(transactions, vmOutput); }
JavaScript
componentWillMount() { // var listingsData = this.listingsData.sort((a, b) => { // We don't have to use this.listingsData because the variable listingsData is being imported above. // Joe decided to use this.state.listingsData because he was having issues with just listingsData. I think the issue would have been solved with an if statement checking for undefined. // if (listingsData != undefined){ // var listingsData = listingsData.sort((a, b) => { // This is going to sort our listings from lowest price to highest price. var listingsData = this.state.listingsData.sort((a, b) => { return a.price - b.price; }); this.setState({ listingsData }); // } }
componentWillMount() { // var listingsData = this.listingsData.sort((a, b) => { // We don't have to use this.listingsData because the variable listingsData is being imported above. // Joe decided to use this.state.listingsData because he was having issues with just listingsData. I think the issue would have been solved with an if statement checking for undefined. // if (listingsData != undefined){ // var listingsData = listingsData.sort((a, b) => { // This is going to sort our listings from lowest price to highest price. var listingsData = this.state.listingsData.sort((a, b) => { return a.price - b.price; }); this.setState({ listingsData }); // } }
JavaScript
change(event) { // Here we say give me the name of whatever it was that we changed. var name = event.target.name; // Here we say give me the value of whatever it was that we changed. // var value = event.target.value; // Here you are checking if this target is a checkbox, or not. If it's a checkbox, then you get the event.target.checked, if not, you get the event.target.value. var value = (event.target.type === "checkbox") ? event.target.checked : event.target.value; // Here we are changing the state. We are setting it to whatever the name of the input field is. And then, the property inside of it will be the value of it. // We want to set up that the filteredData() gets triggered whenever we change the state. Whenever we are changing the state on any of the FILTER options, after it changes the state, we want it to basically trigger the filteredData(). This is going to change the state again, but it's going to change it for the filteredData property of this.state. this.setState({ // When we do a change, this is going to set the state. Basically it is going to set the state, it's going to add the new field, this new property to our state. So if we're changing the city, it's going to come here and say city, and then it's going to say the value is Miami. [name]: value, }, () => { // This is a callback function which means it will be triggered after the state is set. // We console.log this so that we can see the state as it changes. console.log(this.state); this.filteredData(); }); // console.log(event.target.name); // console.log(event.target.value); }
change(event) { // Here we say give me the name of whatever it was that we changed. var name = event.target.name; // Here we say give me the value of whatever it was that we changed. // var value = event.target.value; // Here you are checking if this target is a checkbox, or not. If it's a checkbox, then you get the event.target.checked, if not, you get the event.target.value. var value = (event.target.type === "checkbox") ? event.target.checked : event.target.value; // Here we are changing the state. We are setting it to whatever the name of the input field is. And then, the property inside of it will be the value of it. // We want to set up that the filteredData() gets triggered whenever we change the state. Whenever we are changing the state on any of the FILTER options, after it changes the state, we want it to basically trigger the filteredData(). This is going to change the state again, but it's going to change it for the filteredData property of this.state. this.setState({ // When we do a change, this is going to set the state. Basically it is going to set the state, it's going to add the new field, this new property to our state. So if we're changing the city, it's going to come here and say city, and then it's going to say the value is Miami. [name]: value, }, () => { // This is a callback function which means it will be triggered after the state is set. // We console.log this so that we can see the state as it changes. console.log(this.state); this.filteredData(); }); // console.log(event.target.name); // console.log(event.target.value); }
JavaScript
populateForms() { // city // We are going to go up and basically get all of the listings. // We are going to have an array of cities in the cities var. var cities = this.state.listingsData.map((item) => { return item.city; }); // The next thing we want to do is to create a set. // Here we are creating a new set and passing in the cities array to it. // What this is going to do is that it's going to remove the repeats in the array, it will only keep the unique values. cities = new Set(cities); // We want to make cities into an array, because it is currently an object since that is what the Set() creates. We do this by putting cities inside of an array with a spread operator. cities = [...cities]; // The sort() is going to sort the cities from A to Z. cities = cities.sort(); // homeType var homeTypes = this.state.listingsData.map((item) => { return item.homeType; }); homeTypes = new Set(homeTypes); homeTypes = [...homeTypes]; homeTypes = homeTypes.sort(); // bedrooms var bedrooms = this.state.listingsData.map((item) => { return item.rooms; }); bedrooms = new Set(bedrooms); bedrooms = [...bedrooms]; bedrooms = bedrooms.sort(); // Now we have to pass all of this information to the state. this.setState({ populateFormsData: { homeTypes, bedrooms, cities } }, () => { // Right after the object we are doing this console.log for testing purposes, to see what is happening. console.log(this.state); }); }
populateForms() { // city // We are going to go up and basically get all of the listings. // We are going to have an array of cities in the cities var. var cities = this.state.listingsData.map((item) => { return item.city; }); // The next thing we want to do is to create a set. // Here we are creating a new set and passing in the cities array to it. // What this is going to do is that it's going to remove the repeats in the array, it will only keep the unique values. cities = new Set(cities); // We want to make cities into an array, because it is currently an object since that is what the Set() creates. We do this by putting cities inside of an array with a spread operator. cities = [...cities]; // The sort() is going to sort the cities from A to Z. cities = cities.sort(); // homeType var homeTypes = this.state.listingsData.map((item) => { return item.homeType; }); homeTypes = new Set(homeTypes); homeTypes = [...homeTypes]; homeTypes = homeTypes.sort(); // bedrooms var bedrooms = this.state.listingsData.map((item) => { return item.rooms; }); bedrooms = new Set(bedrooms); bedrooms = [...bedrooms]; bedrooms = bedrooms.sort(); // Now we have to pass all of this information to the state. this.setState({ populateFormsData: { homeTypes, bedrooms, cities } }, () => { // Right after the object we are doing this console.log for testing purposes, to see what is happening. console.log(this.state); }); }
JavaScript
viewModal(listingIndex) { this.setState({ modalSelection: listingIndex }); }
viewModal(listingIndex) { this.setState({ modalSelection: listingIndex }); }
JavaScript
closeModal() { this.setState({ modalSelection: -1 }); }
closeModal() { this.setState({ modalSelection: -1 }); }
JavaScript
cities() { // We had to put all of this inside of an if statement to check for undefined because of some things getting executed asynchronously. if (this.props.globalState.populateFormsData.cities != undefined) { // var { populateFormsData } = this.props.globalState; // We had to go one level deeper, to cities, and could not do it with populateFormsData. populateFormsData is an object, but we needed to use an array, cities, so that we could use array methods, like map. var { cities } = this.props.globalState.populateFormsData; console.log(cities); return cities.map((item) => { return ( // Joe decided to use the item for the key, instead of the index, because we are not repeating the names of the cities. <option key={item} value={item}>{item}</option> ); }); } }
cities() { // We had to put all of this inside of an if statement to check for undefined because of some things getting executed asynchronously. if (this.props.globalState.populateFormsData.cities != undefined) { // var { populateFormsData } = this.props.globalState; // We had to go one level deeper, to cities, and could not do it with populateFormsData. populateFormsData is an object, but we needed to use an array, cities, so that we could use array methods, like map. var { cities } = this.props.globalState.populateFormsData; console.log(cities); return cities.map((item) => { return ( // Joe decided to use the item for the key, instead of the index, because we are not repeating the names of the cities. <option key={item} value={item}>{item}</option> ); }); } }
JavaScript
function documentReady(callback) { if (/complete|loaded|interactive/.test(document.readyState)) callback(); else document.addEventListener('DOMContentLoaded', callback, false); }
function documentReady(callback) { if (/complete|loaded|interactive/.test(document.readyState)) callback(); else document.addEventListener('DOMContentLoaded', callback, false); }
JavaScript
function _parseLisp(tokens, start) { if (start === undefined) start = 0; if (tokens[start].match(/^-?[0123456789]/)) return [parseFloat(tokens[start]), 1]; if (tokens[start] === '(') return parseList(tokens, start); return [tokens[start], 1]; }
function _parseLisp(tokens, start) { if (start === undefined) start = 0; if (tokens[start].match(/^-?[0123456789]/)) return [parseFloat(tokens[start]), 1]; if (tokens[start] === '(') return parseList(tokens, start); return [tokens[start], 1]; }
JavaScript
function parseList(tokens, start) { var index = start; var content = []; if (tokens[index++] !== '(') throw new Error('parseList called on non-list'); while (tokens[index] !== ')') { var res = _parseLisp(tokens, index); content.push(res[0]); index += res[1]; } index++; return [content, index - start]; }
function parseList(tokens, start) { var index = start; var content = []; if (tokens[index++] !== '(') throw new Error('parseList called on non-list'); while (tokens[index] !== ')') { var res = _parseLisp(tokens, index); content.push(res[0]); index += res[1]; } index++; return [content, index - start]; }
JavaScript
function loadJob() { var baseUrl = readBaseUrl(); var cookie = readCookie(); var colLinks = document.getElementsByTagName("A"); var nb = 0; for (var i=0; i<colLinks.length; ++i) { var oLink = colLinks[i]; // improve XSL to have an other criterium, eg a class var bResultPageLink = (oLink.innerHTML == "Resulting page") var bGroupResultPageLink = (oLink.innerHTML == "last result page of this group") if (bResultPageLink || bGroupResultPageLink) { oLink.onclick = handleResultLinkClick; oLink.title += " (Ctrl+mouse over: preview floating over this page, Ctrl+Click: opens in results browser)"; oLink.onmouseover = handleResultMouseOver; oLink.onmouseout = handleResultMouseOut; addReferenceParameters(oLink, baseUrl, cookie); if (bResultPageLink) { var newResult = { resultFilename: oLink.href, link: oLink, index: tabResultLinks.length, tabResultLinks: tabResultLinks }; tabResultLinks[tabResultLinks.length] = newResult; mapHRef2Links[oLink.href] = oLink } ++nb; } } }
function loadJob() { var baseUrl = readBaseUrl(); var cookie = readCookie(); var colLinks = document.getElementsByTagName("A"); var nb = 0; for (var i=0; i<colLinks.length; ++i) { var oLink = colLinks[i]; // improve XSL to have an other criterium, eg a class var bResultPageLink = (oLink.innerHTML == "Resulting page") var bGroupResultPageLink = (oLink.innerHTML == "last result page of this group") if (bResultPageLink || bGroupResultPageLink) { oLink.onclick = handleResultLinkClick; oLink.title += " (Ctrl+mouse over: preview floating over this page, Ctrl+Click: opens in results browser)"; oLink.onmouseover = handleResultMouseOver; oLink.onmouseout = handleResultMouseOut; addReferenceParameters(oLink, baseUrl, cookie); if (bResultPageLink) { var newResult = { resultFilename: oLink.href, link: oLink, index: tabResultLinks.length, tabResultLinks: tabResultLinks }; tabResultLinks[tabResultLinks.length] = newResult; mapHRef2Links[oLink.href] = oLink } ++nb; } } }
JavaScript
function handleResultLinkClick(_event) { var event = _event ? _event : window.event; if (event.ctrlKey) { window.selectedLink = mapHRef2Links[this.href]; // compute the location of the html file: in the same dir as this js file but maybe not in the same dir as the report var oScript = document.getElementById("scriptResponseBrowser"); var strResponseBrowserHref = oScript.src.replace(".js", ".html"); // -> responseBrowser.html in the right dir // Shift gives the possibility to open a new Overview window. This may be usefull to compare 2 results films var targetWindowName = event.shiftKey ? "_blank" : "overview"; window.open(strResponseBrowserHref, targetWindowName); event.cancelBubble = true; return false; } // normal click, do nothing return true; }
function handleResultLinkClick(_event) { var event = _event ? _event : window.event; if (event.ctrlKey) { window.selectedLink = mapHRef2Links[this.href]; // compute the location of the html file: in the same dir as this js file but maybe not in the same dir as the report var oScript = document.getElementById("scriptResponseBrowser"); var strResponseBrowserHref = oScript.src.replace(".js", ".html"); // -> responseBrowser.html in the right dir // Shift gives the possibility to open a new Overview window. This may be usefull to compare 2 results films var targetWindowName = event.shiftKey ? "_blank" : "overview"; window.open(strResponseBrowserHref, targetWindowName); event.cancelBubble = true; return false; } // normal click, do nothing return true; }
JavaScript
function handleResultMouseOver(_event) { var event = _event ? _event : window.event; if (event.ctrlKey) { showPreview(this); } }
function handleResultMouseOver(_event) { var event = _event ? _event : window.event; if (event.ctrlKey) { showPreview(this); } }
JavaScript
function handleResultMouseOut(_event) { if (window.oPreviewDiv != null) { window.oPreviewDiv.style.visibility = "hidden"; } }
function handleResultMouseOut(_event) { if (window.oPreviewDiv != null) { window.oPreviewDiv.style.visibility = "hidden"; } }
JavaScript
function showPreview(_oLink) { var bIsIE = (document.all != null); // IE CSS support is not that good if (window.oPreviewDiv == null) { window.oPreviewDiv = document.createElement("div"); oPreviewDiv.id = "previewDiv"; document.body.appendChild(oPreviewDiv); oPreviewDiv.style.position = "fixed"; oPreviewDiv.style.backgroundColor = "white"; oPreviewDiv.style.borderStyle = "solid"; oPreviewDiv.style.borderWidth = "5pt"; oPreviewDiv.style.borderColor = "blue"; oPreviewDiv.style.width = "70%"; oPreviewDiv.style.height = "90%"; oPreviewDiv.style.left = "28%"; oPreviewDiv.style.top = "5%"; oPreviewDiv.style.zIndex = 100; window.oIframe = document.createElement("iframe"); oPreviewDiv.appendChild(oIframe); oIframe.style.width = "100%"; oIframe.style.height = "100%"; oIframe.style.overflow = "hidden"; if (bIsIE) { oPreviewDiv.style.position = "absolute"; oPreviewDiv.style.width = screen.width * 0.7; oPreviewDiv.style.height = screen.height * 0.9; oIframe.style.overflowY = "hidden"; oIframe.style.overflowX = "hidden"; } } oIframe.src = _oLink.href; oPreviewDiv.style.visibility = "visible"; if (bIsIE) { oPreviewDiv.style.top = document.body.parentElement.scrollTop + screen.height * 0.05; } }
function showPreview(_oLink) { var bIsIE = (document.all != null); // IE CSS support is not that good if (window.oPreviewDiv == null) { window.oPreviewDiv = document.createElement("div"); oPreviewDiv.id = "previewDiv"; document.body.appendChild(oPreviewDiv); oPreviewDiv.style.position = "fixed"; oPreviewDiv.style.backgroundColor = "white"; oPreviewDiv.style.borderStyle = "solid"; oPreviewDiv.style.borderWidth = "5pt"; oPreviewDiv.style.borderColor = "blue"; oPreviewDiv.style.width = "70%"; oPreviewDiv.style.height = "90%"; oPreviewDiv.style.left = "28%"; oPreviewDiv.style.top = "5%"; oPreviewDiv.style.zIndex = 100; window.oIframe = document.createElement("iframe"); oPreviewDiv.appendChild(oIframe); oIframe.style.width = "100%"; oIframe.style.height = "100%"; oIframe.style.overflow = "hidden"; if (bIsIE) { oPreviewDiv.style.position = "absolute"; oPreviewDiv.style.width = screen.width * 0.7; oPreviewDiv.style.height = screen.height * 0.9; oIframe.style.overflowY = "hidden"; oIframe.style.overflowX = "hidden"; } } oIframe.src = _oLink.href; oPreviewDiv.style.visibility = "visible"; if (bIsIE) { oPreviewDiv.style.top = document.body.parentElement.scrollTop + screen.height * 0.05; } }
JavaScript
function readCookie() { var cookieProperty = "wtSessionCookie"; var baseXpath = "//td[@class = 'parameterValue' and text() = '" + cookieProperty + "']/../../tr/td[@class = 'parameterName' and text() = '@myParam@']/following-sibling::td/text()"; var value = evaluateXPath(baseXpath.replace("@myParam@", "-> cookie value")); if (!value) return null; var name = evaluateXPath(baseXpath.replace("@myParam@", "name")); return {'name': name, 'value': value}; }
function readCookie() { var cookieProperty = "wtSessionCookie"; var baseXpath = "//td[@class = 'parameterValue' and text() = '" + cookieProperty + "']/../../tr/td[@class = 'parameterName' and text() = '@myParam@']/following-sibling::td/text()"; var value = evaluateXPath(baseXpath.replace("@myParam@", "-> cookie value")); if (!value) return null; var name = evaluateXPath(baseXpath.replace("@myParam@", "name")); return {'name': name, 'value': value}; }
JavaScript
function evaluateXPath(_strXPath) { if (document.evaluate) return document.evaluate(_strXPath, document, null, XPathResult.STRING_TYPE, null).stringValue; // TODO: make it for IE too return null; }
function evaluateXPath(_strXPath) { if (document.evaluate) return document.evaluate(_strXPath, document, null, XPathResult.STRING_TYPE, null).stringValue; // TODO: make it for IE too return null; }
JavaScript
function addReferenceParameters(_oLink, _baseUrl, _cookie) { if (!_baseUrl) return; var newHref = _oLink.getAttribute("href") + "?baseUrl=" + escape(_baseUrl) if (_cookie) { newHref += "&cookieName=" + escape(_cookie.name) newHref += "&cookieValue=" + escape(_cookie.value) } _oLink.setAttribute("href", newHref) }
function addReferenceParameters(_oLink, _baseUrl, _cookie) { if (!_baseUrl) return; var newHref = _oLink.getAttribute("href") + "?baseUrl=" + escape(_baseUrl) if (_cookie) { newHref += "&cookieName=" + escape(_cookie.name) newHref += "&cookieValue=" + escape(_cookie.value) } _oLink.setAttribute("href", newHref) }
JavaScript
function locateTestSpecTable(imageForTestSpec) { var pContainingStepsOfTestspec = imageForTestSpec.parentNode; do { pContainingStepsOfTestspec = pContainingStepsOfTestspec.nextSibling; // Note: nodeType==1 denotes Elements; see e.g. <http://www.zytrax.com/tech/dom/nodetype.html> } while (pContainingStepsOfTestspec.nodeType != 1); return pContainingStepsOfTestspec; }
function locateTestSpecTable(imageForTestSpec) { var pContainingStepsOfTestspec = imageForTestSpec.parentNode; do { pContainingStepsOfTestspec = pContainingStepsOfTestspec.nextSibling; // Note: nodeType==1 denotes Elements; see e.g. <http://www.zytrax.com/tech/dom/nodetype.html> } while (pContainingStepsOfTestspec.nodeType != 1); return pContainingStepsOfTestspec; }
JavaScript
function showTargetStep(link) { if (link.href.indexOf("#") > -1) { showStep(getNamedAnchor(link.href.substr(link.href.indexOf("#") + 1))); } // lets the browser follows the link return false; }
function showTargetStep(link) { if (link.href.indexOf("#") > -1) { showStep(getNamedAnchor(link.href.substr(link.href.indexOf("#") + 1))); } // lets the browser follows the link return false; }
JavaScript
function toggleDisplayNext(_node, _type) { var oNode = findNext(_node, _type); if (oNode) { var bDisplayed = (oNode.style.display != "none"); oNode.style.display = bDisplayed ? "none" : "inline"; var oImg = findToggleImage(_node); if (oImg) { var newFileName = bDisplayed ? "expandPlus.png" : "expandMinus.png"; oImg.src = oImg.src.replace(/[^/]*$/, newFileName); oImg.alt = bDisplayed ? "Show " : "Hide "; } } }
function toggleDisplayNext(_node, _type) { var oNode = findNext(_node, _type); if (oNode) { var bDisplayed = (oNode.style.display != "none"); oNode.style.display = bDisplayed ? "none" : "inline"; var oImg = findToggleImage(_node); if (oImg) { var newFileName = bDisplayed ? "expandPlus.png" : "expandMinus.png"; oImg.src = oImg.src.replace(/[^/]*$/, newFileName); oImg.alt = bDisplayed ? "Show " : "Hide "; } } }
JavaScript
function findNext(_node, _nodeName) { var nextNode = _node.nextSibling; while (nextNode != null && nextNode.nodeName != _nodeName) { nextNode = nextNode.nextSibling; } return nextNode; }
function findNext(_node, _nodeName) { var nextNode = _node.nextSibling; while (nextNode != null && nextNode.nodeName != _nodeName) { nextNode = nextNode.nextSibling; } return nextNode; }
JavaScript
function findToggleImage(_oNode) { if (_oNode.tagName == "IMG") { return _oNode; } var imgs = _oNode.getElementsByTagName("img"); return (imgs.length > 0) ? imgs[0] : null; }
function findToggleImage(_oNode) { if (_oNode.tagName == "IMG") { return _oNode; } var imgs = _oNode.getElementsByTagName("img"); return (imgs.length > 0) ? imgs[0] : null; }
JavaScript
function changeColors(color) { for(var i =0; i< squares.length; i++) { squares[i].style.backgroundColor = color; } }
function changeColors(color) { for(var i =0; i< squares.length; i++) { squares[i].style.backgroundColor = color; } }