_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q58600
|
warn
|
validation
|
function warn(msg) {
if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
console.log('Warning: ' + msg);
}
}
|
javascript
|
{
"resource": ""
}
|
q58601
|
error
|
validation
|
function error(msg) {
// If multiple arguments were passed, pass them all to the log function.
if (arguments.length > 1) {
var logArguments = ['Error:'];
logArguments.push.apply(logArguments, arguments);
console.log.apply(console, logArguments);
// Join the arguments into a single string for the lines below.
msg = [].join.call(arguments, ' ');
} else {
console.log('Error: ' + msg);
}
console.log(backtrace());
UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
throw new Error(msg);
}
|
javascript
|
{
"resource": ""
}
|
q58602
|
combineUrl
|
validation
|
function combineUrl(baseUrl, url) {
if (!url) {
return baseUrl;
}
if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
return url;
}
var i;
if (url.charAt(0) === '/') {
// absolute path
i = baseUrl.indexOf('://');
if (url.charAt(1) === '/') {
++i;
} else {
i = baseUrl.indexOf('/', i + 3);
}
return baseUrl.substring(0, i) + url;
} else {
// relative path
var pathLength = baseUrl.length;
i = baseUrl.lastIndexOf('#');
pathLength = i >= 0 ? i : pathLength;
i = baseUrl.lastIndexOf('?', pathLength);
pathLength = i >= 0 ? i : pathLength;
var prefixLength = baseUrl.lastIndexOf('/', pathLength);
return baseUrl.substring(0, prefixLength + 1) + url;
}
}
|
javascript
|
{
"resource": ""
}
|
q58603
|
PageViewPort_clone
|
validation
|
function PageViewPort_clone(args) {
args = args || {};
var scale = 'scale' in args ? args.scale : this.scale;
var rotation = 'rotation' in args ? args.rotation : this.rotation;
return new PageViewport(this.viewBox.slice(), scale, rotation,
this.offsetX, this.offsetY, args.dontFlip);
}
|
javascript
|
{
"resource": ""
}
|
q58604
|
PageViewport_convertToViewportRectangle
|
validation
|
function PageViewport_convertToViewportRectangle(rect) {
var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
var br = Util.applyTransform([rect[2], rect[3]], this.transform);
return [tl[0], tl[1], br[0], br[1]];
}
|
javascript
|
{
"resource": ""
}
|
q58605
|
createPromiseCapability
|
validation
|
function createPromiseCapability() {
var capability = {};
capability.promise = new Promise(function (resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
});
return capability;
}
|
javascript
|
{
"resource": ""
}
|
q58606
|
messageHandlerSend
|
validation
|
function messageHandlerSend(actionName, data, transfers) {
var message = {
action: actionName,
data: data
};
this.postMessage(message, transfers);
}
|
javascript
|
{
"resource": ""
}
|
q58607
|
messageHandlerSendWithPromise
|
validation
|
function messageHandlerSendWithPromise(actionName, data, transfers) {
var callbackId = this.callbackIndex++;
var message = {
action: actionName,
data: data,
callbackId: callbackId
};
var capability = createPromiseCapability();
this.callbacksCapabilities[callbackId] = capability;
try {
this.postMessage(message, transfers);
} catch (e) {
capability.reject(e);
}
return capability.promise;
}
|
javascript
|
{
"resource": ""
}
|
q58608
|
validation
|
function (message, transfers) {
if (transfers && this.postMessageTransfers) {
this.comObj.postMessage(message, transfers);
} else {
this.comObj.postMessage(message);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58609
|
hookCallbacks
|
validation
|
function hookCallbacks(stackHelper) {
let stack = stackHelper._stack;
// hook up callbacks
controls.addEventListener('OnScroll', function(e) {
if (e.delta > 0) {
if (stackHelper.index >= stackHelper.orientationMaxIndex - 1) {
return false;
}
stackHelper.index += 1;
} else {
if (stackHelper.index <= 0) {
return false;
}
stackHelper.index -= 1;
}
});
/**
* On window resize callback
*/
function onWindowResize() {
let threeD = document.getElementById('r3d');
camera.canvas = {
width: threeD.clientWidth,
height: threeD.clientHeight,
};
camera.fitBox(2);
renderer.setSize(threeD.clientWidth, threeD.clientHeight);
// update info to draw borders properly
stackHelper.slice.canvasWidth = threeD.clientWidth;
stackHelper.slice.canvasHeight = threeD.clientHeight;
}
window.addEventListener('resize', onWindowResize, false);
onWindowResize();
/**
* On key pressed callback
*/
function onWindowKeyPressed(event) {
ctrlDown = event.ctrlKey;
if (!ctrlDown) {
drag.start.x = null;
drag.start.y = null;
}
}
document.addEventListener('keydown', onWindowKeyPressed, false);
document.addEventListener('keyup', onWindowKeyPressed, false);
/**
* On mouse move callback
*/
function onMouseMove(event) {
if (ctrlDown) {
if (drag.start.x === null) {
drag.start.x = event.clientX;
drag.start.y = event.clientY;
}
let threshold = 15;
stackHelper.slice.intensityAuto = false;
let dynamicRange = stack.minMax[1] - stack.minMax[0];
dynamicRange /= threeD.clientWidth;
if (Math.abs(event.clientX - drag.start.x) > threshold) {
// window width
stackHelper.slice.windowWidth += dynamicRange * (event.clientX - drag.start.x);
drag.start.x = event.clientX;
}
if (Math.abs(event.clientY - drag.start.y) > threshold) {
// window center
stackHelper.slice.windowCenter -= dynamicRange * (event.clientY - drag.start.y);
drag.start.y = event.clientY;
}
}
}
document.addEventListener('mousemove', onMouseMove);
}
|
javascript
|
{
"resource": ""
}
|
q58610
|
onWindowResize
|
validation
|
function onWindowResize() {
let threeD = document.getElementById('r3d');
camera.canvas = {
width: threeD.clientWidth,
height: threeD.clientHeight,
};
camera.fitBox(2);
renderer.setSize(threeD.clientWidth, threeD.clientHeight);
// update info to draw borders properly
stackHelper.slice.canvasWidth = threeD.clientWidth;
stackHelper.slice.canvasHeight = threeD.clientHeight;
}
|
javascript
|
{
"resource": ""
}
|
q58611
|
onWindowKeyPressed
|
validation
|
function onWindowKeyPressed(event) {
ctrlDown = event.ctrlKey;
if (!ctrlDown) {
drag.start.x = null;
drag.start.y = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q58612
|
onMouseMove
|
validation
|
function onMouseMove(event) {
if (ctrlDown) {
if (drag.start.x === null) {
drag.start.x = event.clientX;
drag.start.y = event.clientY;
}
let threshold = 15;
stackHelper.slice.intensityAuto = false;
let dynamicRange = stack.minMax[1] - stack.minMax[0];
dynamicRange /= threeD.clientWidth;
if (Math.abs(event.clientX - drag.start.x) > threshold) {
// window width
stackHelper.slice.windowWidth += dynamicRange * (event.clientX - drag.start.x);
drag.start.x = event.clientX;
}
if (Math.abs(event.clientY - drag.start.y) > threshold) {
// window center
stackHelper.slice.windowCenter -= dynamicRange * (event.clientY - drag.start.y);
drag.start.y = event.clientY;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58613
|
handleSeries
|
validation
|
function handleSeries(seriesContainer) {
// cleanup the loader and its progress bar
loader.free();
loader = null;
// prepare for slice visualization
// first stack of first series
let stack = seriesContainer[0].mergeSeries(seriesContainer)[0].stack[0];
let stackHelper = new HelpersStack(stack);
stackHelper.bbox.visible = false;
stackHelper.borderColor = '#2196F3';
stackHelper.border.visible = false;
scene.add(stackHelper);
// set camera
let worldbb = stack.worldBoundingBox();
let lpsDims = new THREE.Vector3(
(worldbb[1] - worldbb[0]) / 2,
(worldbb[3] - worldbb[2]) / 2,
(worldbb[5] - worldbb[4]) / 2
);
// box: {halfDimensions, center}
let box = {
center: stack.worldCenter().clone(),
halfDimensions: new THREE.Vector3(lpsDims.x + 10, lpsDims.y + 10, lpsDims.z + 10),
};
// init and zoom
let canvas = {
width: threeD.clientWidth,
height: threeD.clientHeight,
};
camera.directions = [stack.xCosine, stack.yCosine, stack.zCosine];
camera.box = box;
camera.canvas = canvas;
camera.update();
camera.fitBox(2);
updateLabels(camera.directionsLabel, stack.modality);
buildGUI(stackHelper);
hookCallbacks(stackHelper);
}
|
javascript
|
{
"resource": ""
}
|
q58614
|
loadSequenceGroup
|
validation
|
function loadSequenceGroup(files) {
const fetchSequence = [];
for (let i = 0; i < files.length; i++) {
fetchSequence.push(
new Promise((resolve, reject) => {
const myReader = new FileReader();
// should handle errors too...
myReader.addEventListener('load', function(e) {
resolve(e.target.result);
});
myReader.readAsArrayBuffer(files[i].file);
}).then(function(buffer) {
return { url: files[i].file.name, buffer };
})
);
}
return Promise.all(fetchSequence)
.then(rawdata => {
return loader.parse(rawdata);
})
.then(function(series) {
seriesContainer.push(series);
})
.catch(function(error) {
window.console.log('oops... something went wrong...');
window.console.log(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q58615
|
init
|
validation
|
function init() {
/**
* Animation loop
*/
function animate() {
updateGeometries();
render();
// request new frame
requestAnimationFrame(function() {
animate();
});
}
// renderer
threeD = document.getElementById('r3d');
renderer = new THREE.WebGLRenderer({
antialias: true,
});
renderer.setSize(threeD.offsetWidth, threeD.offsetHeight);
renderer.setClearColor(0x353535, 1);
renderer.setPixelRatio(window.devicePixelRatio);
threeD.appendChild(renderer.domElement);
// stats
stats = new Stats();
threeD.appendChild(stats.domElement);
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera(
45,
threeD.offsetWidth / threeD.offsetHeight,
0.01,
10000000
);
camera.position.x = 150;
camera.position.y = 150;
camera.position.z = 100;
// controls
controls = new ControlsTrackball(camera, threeD);
controls.rotateSpeed = 1.4;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.dynamicDampingFactor = 0.3;
particleLight = new THREE.Mesh(
new THREE.SphereGeometry(2, 8, 8),
new THREE.MeshBasicMaterial({ color: 0xfff336 })
);
scene.add(particleLight);
animate();
}
|
javascript
|
{
"resource": ""
}
|
q58616
|
init
|
validation
|
function init() {
/**
* Called on each animation frame
*/
function animate() {
render();
// request new frame
requestAnimationFrame(function() {
animate();
});
}
// renderers
initRenderer3D(r0);
initRenderer2D(r1);
initRenderer2D(r2);
initRenderer2D(r3);
// start rendering loop
animate();
}
|
javascript
|
{
"resource": ""
}
|
q58617
|
updateLocalizer
|
validation
|
function updateLocalizer(refObj, targetLocalizersHelpers) {
let refHelper = refObj.stackHelper;
let localizerHelper = refObj.localizerHelper;
let plane = refHelper.slice.cartesianEquation();
localizerHelper.referencePlane = plane;
// bit of a hack... works fine for this application
for (let i = 0; i < targetLocalizersHelpers.length; i++) {
for (let j = 0; j < 3; j++) {
let targetPlane = targetLocalizersHelpers[i]['plane' + (j + 1)];
if (
targetPlane &&
plane.x.toFixed(6) === targetPlane.x.toFixed(6) &&
plane.y.toFixed(6) === targetPlane.y.toFixed(6) &&
plane.z.toFixed(6) === targetPlane.z.toFixed(6)
) {
targetLocalizersHelpers[i]['plane' + (j + 1)] = plane;
}
}
}
// update the geometry will create a new mesh
localizerHelper.geometry = refHelper.slice.geometry;
}
|
javascript
|
{
"resource": ""
}
|
q58618
|
mapCanvasToData
|
validation
|
function mapCanvasToData() {
for (let i = ijkBBox[0]; i < ijkBBox[1] + 1; i++) {
for (let j = ijkBBox[2]; j < ijkBBox[3] + 1; j++) {
for (let k = ijkBBox[4]; k < ijkBBox[5] + 1; k++) {
// ijk to world
// center of voxel
let worldCoordinate = new THREE.Vector3(i, j, k).applyMatrix4(stack2._ijk2LPS);
// world to screen coordinate
let screenCoordinates = worldCoordinate.clone();
screenCoordinates.project(camera);
screenCoordinates.x = Math.round(((screenCoordinates.x + 1) * canvas.offsetWidth) / 2);
screenCoordinates.y = Math.round(((-screenCoordinates.y + 1) * canvas.offsetHeight) / 2);
screenCoordinates.z = 0;
let pixel = context.getImageData(screenCoordinates.x, screenCoordinates.y, 1, 1).data;
if (pixel[3] > 0 && i >= 0 && j >= 0 && k >= 0) {
// find index and texture
let voxelIndex = i + j * stack2._columns + k * stack2._rows * stack2._columns;
let textureSize = 4096;
let textureDimension = textureSize * textureSize;
let rawDataIndex = ~~(voxelIndex / textureDimension);
let inRawDataIndex = voxelIndex % textureDimension;
// update value...
let oldValue = stack2.rawData[rawDataIndex][inRawDataIndex];
let newValue = cursor.value;
if (oldValue != newValue) {
// update raw data
stack2.rawData[rawDataIndex][inRawDataIndex] = newValue;
// update texture that is passed to shader
textures2[rawDataIndex].image.data = stack2.rawData[rawDataIndex]; // tex;
textures2[rawDataIndex].needsUpdate = true;
// update stats
editorStats[oldValue] -= 1;
editorStats[newValue] += 1;
}
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58619
|
getShortlinker
|
validation
|
function getShortlinker() {
if ( globalScope.yoast.shortlinker === null ) {
globalScope.yoast.shortlinker = new Shortlinker();
}
return globalScope.yoast.shortlinker;
}
|
javascript
|
{
"resource": ""
}
|
q58620
|
validation
|
function( sentencePartText, auxiliaries, locale ) {
this._sentencePartText = sentencePartText;
this._auxiliaries = auxiliaries;
this._locale = locale;
this._isPassive = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q58621
|
validation
|
function( i18n, options = {} ) {
Assessor.call( this, i18n, options );
this.type = "ContentAssessor";
const locale = ( options.hasOwnProperty( "locale" ) ) ? options.locale : "en_US";
this._assessments = [
new FleschReadingEase( contentConfiguration( locale ).fleschReading ),
new SubheadingDistributionTooLong(),
paragraphTooLong,
new SentenceLengthInText( contentConfiguration( locale ).sentenceLength ),
transitionWords,
passiveVoice,
textPresence,
sentenceBeginnings,
// Temporarily disabled: wordComplexity,
];
}
|
javascript
|
{
"resource": ""
}
|
|
q58622
|
DeviationFragment
|
validation
|
function DeviationFragment( options ) {
this._location = options.location;
this._fragment = options.word;
this._syllables = options.syllables;
this._regex = null;
this._options = pick( options, [ "notFollowedBy", "alsoFollowedBy" ] );
}
|
javascript
|
{
"resource": ""
}
|
q58623
|
sortResults
|
validation
|
function sortResults( assessmentResults ) {
return assessmentResults.sort( ( a, b ) => {
// First compare the score.
if ( a.score < b.score ) {
return -1;
}
if ( a.score > b.score ) {
return 1;
}
// If there is no difference then compare the id.
return a.id.localeCompare( b.id );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58624
|
mapResult
|
validation
|
function mapResult( result ) {
result.id = result.getIdentifier();
result.rating = scoreToRating( result.score );
result.hasMarks = result.hasMarks();
result.marker = result.getMarker();
// Because of inconsistency between YoastSEO and yoast-components.
if ( result.rating === "ok" ) {
result.rating = "OK";
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58625
|
mapResults
|
validation
|
function mapResults( results ) {
const mappedResults = [];
for ( let i = 0; i < results.length; i++ ) {
if ( ! results[ i ].text ) {
continue;
}
mappedResults.push( mapResult( results[ i ] ) );
}
return sortResults( mappedResults );
}
|
javascript
|
{
"resource": ""
}
|
q58626
|
validation
|
function( participle, sentencePart, attributes ) {
Participle.call( this, participle, sentencePart, attributes );
this.setSentencePartPassiveness( this.isPassive() );
}
|
javascript
|
{
"resource": ""
}
|
|
q58627
|
validation
|
function( args ) {
this.keyword = args.keyword;
this.assessor = args.assessor;
this.i18n = args.i18n;
this.output = args.targets.output;
this.overall = args.targets.overall || "overallScore";
this.presenterConfig = createConfig( args.i18n );
this._disableMarkerButtons = false;
this._activeMarker = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q58628
|
getBlocks
|
validation
|
function getBlocks( text ) {
var blocks = [], depth = 0,
blockStartTag = "",
currentBlock = "",
blockEndTag = "";
// Remove all comments because it is very hard to tokenize them.
text = text.replace( commentRegex, "" );
createTokenizer();
htmlBlockTokenizer.onText( text );
htmlBlockTokenizer.end();
forEach( tokens, function( token, i ) {
var nextToken = tokens[ i + 1 ];
switch ( token.type ) {
case "content":
case "greater-than-sign-content":
case "inline-start":
case "inline-end":
case "other-tag":
case "other-element-start":
case "other-element-end":
case "greater than sign":
if ( ! nextToken || ( depth === 0 && ( nextToken.type === "block-start" || nextToken.type === "block-end" ) ) ) {
currentBlock += token.src;
blocks.push( currentBlock );
blockStartTag = "";
currentBlock = "";
blockEndTag = "";
} else {
currentBlock += token.src;
}
break;
case "block-start":
if ( depth !== 0 ) {
if ( currentBlock.trim() !== "" ) {
blocks.push( currentBlock );
}
currentBlock = "";
blockEndTag = "";
}
depth++;
blockStartTag = token.src;
break;
case "block-end":
depth--;
blockEndTag = token.src;
/*
* We try to match the most deep blocks so discard any other blocks that have been started but not
* finished.
*/
if ( "" !== blockStartTag && "" !== blockEndTag ) {
blocks.push( blockStartTag + currentBlock + blockEndTag );
} else if ( "" !== currentBlock.trim() ) {
blocks.push( currentBlock );
}
blockStartTag = "";
currentBlock = "";
blockEndTag = "";
break;
}
// Handles HTML with too many closing tags.
if ( depth < 0 ) {
depth = 0;
}
} );
return blocks;
}
|
javascript
|
{
"resource": ""
}
|
q58629
|
formatNumber
|
validation
|
function formatNumber( number ) {
if ( Math.round( number ) === number ) {
return number;
}
return Math.round( number * 10000 ) / 10000;
}
|
javascript
|
{
"resource": ""
}
|
q58630
|
validation
|
function( participle, sentencePart, attributes ) {
Participle.call( this, participle, sentencePart, attributes );
checkException.call( this );
}
|
javascript
|
{
"resource": ""
}
|
|
q58631
|
validation
|
function( participleExceptionRegexes ) {
var participle = this.getParticiple();
var match = [];
forEach( participleExceptionRegexes, function( participleExceptionRegex ) {
var exceptionMatch = participle.match( participleExceptionRegex );
if ( exceptionMatch ) {
match.push( exceptionMatch[ 0 ] );
}
} );
if ( match.length > 0 ) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q58632
|
getSentenceBeginning
|
validation
|
function getSentenceBeginning( sentence, firstWordExceptions ) {
const words = getWords( stripTags( stripSpaces( sentence ) ) );
if ( words.length === 0 ) {
return "";
}
let firstWord = words[ 0 ].toLocaleLowerCase();
if ( firstWordExceptions.indexOf( firstWord ) > -1 && words.length > 1 ) {
firstWord += " " + words[ 1 ];
}
return firstWord;
}
|
javascript
|
{
"resource": ""
}
|
q58633
|
textPresenceAssessment
|
validation
|
function textPresenceAssessment( paper, researcher, i18n ) {
const text = stripHTMLTags( paper.getText() );
const urlTitle = createAnchorOpeningTag( "https://yoa.st/35h" );
const urlCallToAction = createAnchorOpeningTag( "https://yoa.st/35i" );
if ( text.length < 50 ) {
const result = new AssessmentResult();
result.setText( i18n.sprintf(
/* Translators: %1$s and %3$s expand to links to articles on Yoast.com,
%2$s expands to the anchor end tag*/
i18n.dgettext( "js-text-analysis",
"%1$sNot enough content%2$s: %3$sPlease add some content to enable a good analysis%2$s." ),
urlTitle,
"</a>",
urlCallToAction ) );
result.setScore( 3 );
return result;
}
return new AssessmentResult();
}
|
javascript
|
{
"resource": ""
}
|
q58634
|
splitOnWords
|
validation
|
function splitOnWords( sentence, stopwords ) {
const splitSentences = [];
// Split the sentence on each found stopword and push this part in an array.
forEach( stopwords, function( stopword ) {
const sentenceSplit = sentence.split( stopword );
if ( ! isEmpty( sentenceSplit[ 0 ] ) ) {
splitSentences.push( sentenceSplit[ 0 ] );
}
const startIndex = sentence.indexOf( stopword );
const endIndex = sentence.length;
sentence = stripSpaces( sentence.substr( startIndex, endIndex ) );
} );
// Push the remainder of the sentence in the sentence parts array.
splitSentences.push( sentence );
return splitSentences;
}
|
javascript
|
{
"resource": ""
}
|
q58635
|
createSentenceParts
|
validation
|
function createSentenceParts( sentences, language ) {
const auxiliaryRegex = languageVariables[ language ].auxiliaryRegex;
const SentencePart = languageVariables[ language ].SentencePart;
const sentenceParts = [];
forEach( sentences, function( part ) {
const foundAuxiliaries = sanitizeMatches( part.match( auxiliaryRegex || [] ) );
sentenceParts.push( new SentencePart( part, foundAuxiliaries, languageVariables[ language ].locale ) );
} );
return sentenceParts;
}
|
javascript
|
{
"resource": ""
}
|
q58636
|
splitSentence
|
validation
|
function splitSentence( sentence, language ) {
const stopwordRegex = languageVariables[ language ].stopwordRegex;
const stopwords = sentence.match( stopwordRegex ) || [];
const splitSentences = splitOnWords( sentence, stopwords );
return createSentenceParts( splitSentences, language );
}
|
javascript
|
{
"resource": ""
}
|
q58637
|
createDefaultSnippetPreview
|
validation
|
function createDefaultSnippetPreview() {
var targetElement = document.getElementById( this.config.targets.snippet );
return new SnippetPreview( {
analyzerApp: this,
targetElement: targetElement,
callbacks: {
saveSnippetData: this.config.callbacks.saveSnippetData,
},
} );
}
|
javascript
|
{
"resource": ""
}
|
q58638
|
verifyArguments
|
validation
|
function verifyArguments( args ) {
if ( ! isObject( args.callbacks.getData ) ) {
throw new MissingArgument( "The app requires an object with a getdata callback." );
}
if ( ! isObject( args.targets ) ) {
throw new MissingArgument( "`targets` is a required App argument, `targets` is not an object." );
}
// The args.targets.snippet argument is only required if not SnippetPreview object has been passed.
if (
args.hasSnippetPreview &&
! isValidSnippetPreview( args.snippetPreview ) &&
! isString( args.targets.snippet ) ) {
throw new MissingArgument( "A snippet preview is required. When no SnippetPreview object isn't passed to " +
"the App, the `targets.snippet` is a required App argument. `targets.snippet` is not a string." );
}
}
|
javascript
|
{
"resource": ""
}
|
q58639
|
getWordCombinations
|
validation
|
function getWordCombinations( text, combinationSize, functionWords ) {
const sentences = getSentences( text );
let words, combination;
return flatMap( sentences, function( sentence ) {
sentence = sentence.toLocaleLowerCase();
sentence = normalizeQuotes( sentence );
words = getWords( sentence );
return filter( map( words, function( word, i ) {
// If there are still enough words in the sentence to slice of.
if ( i + combinationSize - 1 < words.length ) {
combination = words.slice( i, i + combinationSize );
return new WordCombination( combination, 0, functionWords );
}
return false;
} ) );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58640
|
calculateOccurrences
|
validation
|
function calculateOccurrences( wordCombinations ) {
const occurrences = {};
forEach( wordCombinations, function( wordCombination ) {
const combination = wordCombination.getCombination();
if ( ! has( occurrences, combination ) ) {
occurrences[ combination ] = wordCombination;
}
occurrences[ combination ].incrementOccurrences();
} );
return values( occurrences );
}
|
javascript
|
{
"resource": ""
}
|
q58641
|
getRelevantCombinations
|
validation
|
function getRelevantCombinations( wordCombinations ) {
wordCombinations = wordCombinations.filter( function( combination ) {
return combination.getOccurrences() !== 1 &&
combination.getRelevance() !== 0;
} );
return wordCombinations;
}
|
javascript
|
{
"resource": ""
}
|
q58642
|
sortCombinations
|
validation
|
function sortCombinations( wordCombinations ) {
wordCombinations.sort( function( combinationA, combinationB ) {
const difference = combinationB.getRelevance() - combinationA.getRelevance();
// The combination with the highest relevance comes first.
if ( difference !== 0 ) {
return difference;
}
// In case of a tie on relevance, the longest combination comes first.
return combinationB.getLength() - combinationA.getLength();
} );
}
|
javascript
|
{
"resource": ""
}
|
q58643
|
filterOneCharacterWordCombinations
|
validation
|
function filterOneCharacterWordCombinations( wordCombinations ) {
return wordCombinations.filter( function( combination ) {
return ! ( combination.getLength() === 1 && combination.getWords()[ 0 ].length <= 1 );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58644
|
filterFunctionWordsAnywhere
|
validation
|
function filterFunctionWordsAnywhere( wordCombinations, functionWords ) {
return wordCombinations.filter( function( combination ) {
return isEmpty(
intersection( functionWords, combination.getWords() )
);
} );
}
|
javascript
|
{
"resource": ""
}
|
q58645
|
filterFunctionWordsAtBeginning
|
validation
|
function filterFunctionWordsAtBeginning( wordCombinations, functionWords ) {
return wordCombinations.filter( function( combination ) {
return ! includes( functionWords, combination.getWords()[ 0 ] );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58646
|
filterFunctionWordsAtEnding
|
validation
|
function filterFunctionWordsAtEnding( wordCombinations, functionWords ) {
return wordCombinations.filter( function( combination ) {
const words = combination.getWords();
const lastWordIndex = words.length - 1;
return ! includes( functionWords, words[ lastWordIndex ] );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58647
|
filterFunctionWordsAtBeginningAndEnding
|
validation
|
function filterFunctionWordsAtBeginningAndEnding( wordCombinations, functionWords ) {
wordCombinations = filterFunctionWordsAtBeginning( wordCombinations, functionWords );
wordCombinations = filterFunctionWordsAtEnding( wordCombinations, functionWords );
return wordCombinations;
}
|
javascript
|
{
"resource": ""
}
|
q58648
|
filterOnDensity
|
validation
|
function filterOnDensity( wordCombinations, wordCount, lowerLimit, upperLimit ) {
return wordCombinations.filter( function( combination ) {
return ( combination.getDensity( wordCount ) >= lowerLimit && combination.getDensity( wordCount ) < upperLimit
);
} );
}
|
javascript
|
{
"resource": ""
}
|
q58649
|
filterEndingWith
|
validation
|
function filterEndingWith( wordCombinations, str, exceptions ) {
wordCombinations = wordCombinations.filter( function( combination ) {
const combinationstr = combination.getCombination();
for ( let i = 0; i < exceptions.length; i++ ) {
if ( combinationstr.endsWith( exceptions[ i ] ) ) {
return true;
}
}
return ! combinationstr.endsWith( str );
} );
return wordCombinations;
}
|
javascript
|
{
"resource": ""
}
|
q58650
|
filterFunctionWords
|
validation
|
function filterFunctionWords( combinations, functionWords ) {
combinations = filterFunctionWordsAnywhere( combinations, functionWords.filteredAnywhere );
combinations = filterFunctionWordsAtBeginningAndEnding( combinations, functionWords.filteredAtBeginningAndEnding );
combinations = filterFunctionWordsAtEnding( combinations, functionWords.filteredAtEnding );
combinations = filterFunctionWordsAtBeginning( combinations, functionWords.filteredAtBeginning );
return combinations;
}
|
javascript
|
{
"resource": ""
}
|
q58651
|
filterCombinations
|
validation
|
function filterCombinations( combinations, functionWords, language ) {
combinations = filterFunctionWordsAnywhere( combinations, specialCharacters );
combinations = filterOneCharacterWordCombinations( combinations );
combinations = filterFunctionWords( combinations, functionWords );
if ( language === "en" ) {
combinations = filterEndingWith( combinations, "'s", [] );
}
return combinations;
}
|
javascript
|
{
"resource": ""
}
|
q58652
|
getRelevantWords
|
validation
|
function getRelevantWords( text, locale ) {
let language = getLanguage( locale );
if ( ! functionWordLists.hasOwnProperty( language ) ) {
language = "en";
}
const functionWords = functionWordLists[ language ];
const words = getWordCombinations( text, 1, functionWords.all );
const wordCount = words.length;
let oneWordCombinations = getRelevantCombinations(
calculateOccurrences( words )
);
sortCombinations( oneWordCombinations );
oneWordCombinations = take( oneWordCombinations, 100 );
const oneWordRelevanceMap = {};
forEach( oneWordCombinations, function( combination ) {
oneWordRelevanceMap[ combination.getCombination() ] = combination.getRelevance();
} );
const twoWordCombinations = calculateOccurrences( getWordCombinations( text, 2, functionWords.all ) );
const threeWordCombinations = calculateOccurrences( getWordCombinations( text, 3, functionWords.all ) );
const fourWordCombinations = calculateOccurrences( getWordCombinations( text, 4, functionWords.all ) );
const fiveWordCombinations = calculateOccurrences( getWordCombinations( text, 5, functionWords.all ) );
let combinations = oneWordCombinations.concat(
twoWordCombinations,
threeWordCombinations,
fourWordCombinations,
fiveWordCombinations
);
combinations = filterCombinations( combinations, functionWords, language );
forEach( combinations, function( combination ) {
combination.setRelevantWords( oneWordRelevanceMap );
} );
combinations = getRelevantCombinations( combinations );
sortCombinations( combinations );
if ( wordCount >= wordCountLowerLimit ) {
combinations = filterOnDensity( combinations, wordCount, densityLowerLimit, densityUpperLimit );
}
return take( combinations, relevantWordLimit );
}
|
javascript
|
{
"resource": ""
}
|
q58653
|
WordCombination
|
validation
|
function WordCombination( words, occurrences, functionWords ) {
this._words = words;
this._length = words.length;
this._occurrences = occurrences || 0;
this._functionWords = functionWords;
}
|
javascript
|
{
"resource": ""
}
|
q58654
|
createAssessment
|
validation
|
function createAssessment( name, score = 9, text = "Excellent" ) {
const assessment = new Assessment();
assessment.identifier = name;
assessment.getResult = () => {
const result = new AssessmentResult();
result.setScore( score );
result.setText( text );
return result;
};
return assessment;
}
|
javascript
|
{
"resource": ""
}
|
q58655
|
MissingArgumentError
|
validation
|
function MissingArgumentError( message ) {
Error.captureStackTrace( this, this.constructor );
this.name = this.constructor.name;
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q58656
|
validation
|
function( participle, sentencePart, attributes ) {
this.setParticiple( participle );
this.setSentencePart( sentencePart );
this._determinesSentencePartIsPassive = false;
attributes = attributes || {};
defaults( attributes, defaultAttributes );
validateAttributes( attributes );
this._attributes = attributes;
}
|
javascript
|
{
"resource": ""
}
|
|
q58657
|
getSubheadingsTopLevel
|
validation
|
function getSubheadingsTopLevel( text ) {
const subheadings = [];
const regex = /<h([2-3])(?:[^>]+)?>(.*?)<\/h\1>/ig;
let match;
while ( ( match = regex.exec( text ) ) !== null ) {
subheadings.push( match );
}
return subheadings;
}
|
javascript
|
{
"resource": ""
}
|
q58658
|
getSentencesFromBlock
|
validation
|
function getSentencesFromBlock( block ) {
const sentenceTokenizer = new SentenceTokenizer();
const { tokenizer, tokens } = sentenceTokenizer.createTokenizer();
sentenceTokenizer.tokenize( tokenizer, block );
return tokens.length === 0 ? [] : sentenceTokenizer.getSentencesFromTokens( tokens );
}
|
javascript
|
{
"resource": ""
}
|
q58659
|
createWorker
|
validation
|
function createWorker( url ) {
let worker = null;
try {
worker = new Worker( url );
} catch ( e ) {
try {
const blobUrl = createBlobURL( url );
worker = new Worker( blobUrl );
} catch ( e2 ) {
throw e2;
}
}
return worker;
}
|
javascript
|
{
"resource": ""
}
|
q58660
|
validation
|
function( i18n, options ) {
this.type = "Assessor";
this.setI18n( i18n );
this._assessments = [];
this._options = options || {};
if ( ! isUndefined( this._options.researcher ) ) {
this._researcher = this._options.researcher;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58661
|
configureStore
|
validation
|
function configureStore( preloadedState = {}, extraMiddleware = [] ) {
const enhancers = configureEnhancers( extraMiddleware );
return createStore( rootReducer, preloadedState, enhancers );
}
|
javascript
|
{
"resource": ""
}
|
q58662
|
removeLinksFromText
|
validation
|
function removeLinksFromText( text ) {
const anchors = getAnchorsFromText( text );
if ( anchors.length > 0 ) {
anchors.forEach( function( anchor ) {
text = text.replace( anchor, "" );
} );
}
return text;
}
|
javascript
|
{
"resource": ""
}
|
q58663
|
removeImagesFromText
|
validation
|
function removeImagesFromText( text ) {
const images = imageInText( text );
const imageTags = matchStringWithRegex( text, "</img>" );
if ( images.length > 0 ) {
images.forEach( function( image ) {
text = text.replace( image, "" );
} );
imageTags.forEach( function( imageTag ) {
text = text.replace( imageTag, "" );
} );
}
return text;
}
|
javascript
|
{
"resource": ""
}
|
q58664
|
paragraphHasNoText
|
validation
|
function paragraphHasNoText( text ) {
// Strip links and check if paragraph consists of links only
text = removeLinksFromText( text );
if ( text === "" ) {
return true;
}
text = removeImagesFromText( text );
if ( text === "" ) {
return true;
}
// Remove empty divisions from the text
const emptyDivisions = findEmptyDivisions( text );
if ( emptyDivisions.length < 1 ) {
return false;
}
emptyDivisions.forEach( function( emptyDivision ) {
text = text.replace( emptyDivision, "" );
} );
return text === "";
}
|
javascript
|
{
"resource": ""
}
|
q58665
|
getRelevantWords
|
validation
|
function getRelevantWords( text, locale ) {
if ( ! isEqual( text, previousRelevantWords.text ) || ! isEqual( locale, previousRelevantWords.locale ) ) {
previousRelevantWords = {
text,
locale,
data: calculateRelevantWords( text, locale ),
};
}
return previousRelevantWords.data;
}
|
javascript
|
{
"resource": ""
}
|
q58666
|
validation
|
function() {
var baseURL = this.opts.baseURL;
/*
* For backwards compatibility, if no URL was passed to the snippet editor we try to retrieve the base URL from the
* rawData in the App. This is because the scrapers used to be responsible for retrieving the baseURL, but the base
* URL is static so we can just pass it to the snippet editor.
*/
if ( this.hasApp() && ! isEmpty( this.refObj.rawData.baseUrl ) && this.opts.baseURL === defaults.baseURL ) {
baseURL = this.refObj.rawData.baseUrl;
}
return baseURL;
}
|
javascript
|
{
"resource": ""
}
|
|
q58667
|
updateUnformattedText
|
validation
|
function updateUnformattedText( key, value ) {
this.element.input[ key ].value = value;
this.data[ key ] = value;
}
|
javascript
|
{
"resource": ""
}
|
q58668
|
rateTitleLength
|
validation
|
function rateTitleLength( titleLength ) {
var rating;
switch ( true ) {
case titleLength > 0 && titleLength <= 399:
case titleLength > 600:
rating = "ok";
break;
case titleLength >= 400 && titleLength <= 600:
rating = "good";
break;
default:
rating = "bad";
break;
}
return rating;
}
|
javascript
|
{
"resource": ""
}
|
q58669
|
rateMetaDescLength
|
validation
|
function rateMetaDescLength( metaDescLength ) {
var rating;
switch ( true ) {
case metaDescLength > 0 && metaDescLength < 120:
case metaDescLength > maximumMetaDescriptionLength:
rating = "ok";
break;
case metaDescLength >= 120 && metaDescLength <= maximumMetaDescriptionLength:
rating = "good";
break;
default:
rating = "bad";
break;
}
return rating;
}
|
javascript
|
{
"resource": ""
}
|
q58670
|
updateProgressBar
|
validation
|
function updateProgressBar( element, value, maximum, rating ) {
var barElement, progress,
allClasses = [
"snippet-editor__progress--bad",
"snippet-editor__progress--ok",
"snippet-editor__progress--good",
];
element.value = value;
domManipulation.removeClasses( element, allClasses );
domManipulation.addClass( element, "snippet-editor__progress--" + rating );
if ( ! this.hasProgressSupport ) {
barElement = element.getElementsByClassName( "snippet-editor__progress-bar" )[ 0 ];
progress = ( value / maximum ) * 100;
barElement.style.width = progress + "%";
}
}
|
javascript
|
{
"resource": ""
}
|
q58671
|
getAnalyzerTitle
|
validation
|
function getAnalyzerTitle() {
var title = this.data.title;
if ( isEmpty( title ) ) {
title = this.opts.defaultValue.title;
}
if ( this.hasPluggable() ) {
title = this.refObj.pluggable._applyModifications( "data_page_title", title );
}
return stripSpaces( title );
}
|
javascript
|
{
"resource": ""
}
|
q58672
|
validation
|
function() {
var metaDesc = this.data.metaDesc;
if ( isEmpty( metaDesc ) ) {
metaDesc = this.opts.defaultValue.metaDesc;
}
if ( this.hasPluggable() ) {
metaDesc = this.refObj.pluggable._applyModifications( "data_meta_desc", metaDesc );
}
if ( ! isEmpty( this.opts.metaDescriptionDate ) && ! isEmpty( metaDesc ) ) {
metaDesc = this.opts.metaDescriptionDate + " - " + this.data.metaDesc;
}
return stripSpaces( metaDesc );
}
|
javascript
|
{
"resource": ""
}
|
|
q58673
|
showTrace
|
validation
|
function showTrace( errorMessage ) {
if ( isUndefined( errorMessage ) ) {
errorMessage = "";
}
if (
! isUndefined( console ) &&
! isUndefined( console.trace )
) {
console.trace( errorMessage );
}
}
|
javascript
|
{
"resource": ""
}
|
q58674
|
getIndicesByWord
|
validation
|
function getIndicesByWord( word, text ) {
var startIndex = 0;
var searchStringLength = word.length;
var index, indices = [];
while ( ( index = text.indexOf( word, startIndex ) ) > -1 ) {
// Check if the previous and next character are word boundaries to determine if a complete word was detected
var isPreviousCharacterWordBoundary = characterInBoundary( text[ index - 1 ] ) || index === 0;
var isNextCharacterWordBoundary = characterInBoundary( text[ index + searchStringLength ] ) || ( text.length === index + searchStringLength );
if ( isPreviousCharacterWordBoundary && isNextCharacterWordBoundary ) {
indices.push(
{
index: index,
match: word,
}
);
}
startIndex = index + searchStringLength;
}
return indices;
}
|
javascript
|
{
"resource": ""
}
|
q58675
|
validation
|
function( words, text ) {
var matchedWords = [];
forEach( words, function( word ) {
word = stripSpaces( word );
if ( ! matchWordInSentence( word, text ) ) {
return;
}
matchedWords = matchedWords.concat( getIndicesByWord( word, text ) );
} );
return matchedWords;
}
|
javascript
|
{
"resource": ""
}
|
|
q58676
|
validation
|
function( indices ) {
indices = sortIndices( indices );
var filtered = [];
for ( var i = 0; i < indices.length; i++ ) {
// If the next index is within the range of the current index and the length of the word, remove it
// This makes sure we don't match combinations twice, like "even though" and "though".
if ( ! isUndefined( indices[ i + 1 ] ) && indices[ i + 1 ].index < indices[ i ].index + indices[ i ].match.length ) {
filtered.push( indices[ i ] );
// Adds 1 to i, so we skip the next index that is overlapping with the current index.
i++;
continue;
}
filtered.push( indices[ i ] );
}
return filtered;
}
|
javascript
|
{
"resource": ""
}
|
|
q58677
|
validation
|
function( words, text ) {
var matchedWords = [];
forEach( words, function( word ) {
word = stripSpaces( word );
if ( ! matchWordInSentence( word, text ) ) {
return matchedWords;
}
matchedWords = matchedWords.concat( getIndicesByWord( word, text ) );
} );
matchedWords = matchedWords.sort( function( a, b ) {
if ( a.index < b.index ) {
return -1;
}
if ( a.index > b.index ) {
return 1;
}
return 0;
} );
return matchedWords;
}
|
javascript
|
{
"resource": ""
}
|
|
q58678
|
createMeasurementElement
|
validation
|
function createMeasurementElement() {
const hiddenElement = document.createElement( "div" );
hiddenElement.id = elementId;
// Styles to prevent unintended scrolling in Gutenberg.
hiddenElement.style.position = "absolute";
hiddenElement.style.left = "-9999em";
hiddenElement.style.top = 0;
hiddenElement.style.height = 0;
hiddenElement.style.overflow = "hidden";
hiddenElement.style.fontFamily = "arial, sans-serif";
hiddenElement.style.fontSize = "18px";
hiddenElement.style.fontWeight = "400";
document.body.appendChild( hiddenElement );
return hiddenElement;
}
|
javascript
|
{
"resource": ""
}
|
q58679
|
validation
|
function( app ) {
this.app = app;
this.loaded = false;
this.preloadThreshold = 3000;
this.plugins = {};
this.modifications = {};
this.customTests = [];
// Allow plugins 1500 ms to register before we start polling their
setTimeout( this._pollLoadingPlugins.bind( this ), 1500 );
}
|
javascript
|
{
"resource": ""
}
|
|
q58680
|
validation
|
function( paper ) {
this.setPaper( paper );
this.defaultResearches = {
urlLength: urlLength,
wordCountInText: wordCountInText,
findKeywordInPageTitle: findKeywordInPageTitle,
calculateFleschReading: calculateFleschReading,
getLinkStatistics: getLinkStatistics,
getLinks: getLinks,
linkCount: linkCount,
imageCount: imageCount,
altTagCount: altTagCount,
matchKeywordInSubheadings: matchKeywordInSubheadings,
keywordCount: keywordCount,
getKeywordDensity: getKeywordDensity,
stopWordsInKeyword: stopWordsInKeyword,
stopWordsInUrl: stopWordsInUrl,
metaDescriptionLength: metaDescriptionLength,
keyphraseLength: keyphraseLength,
keywordCountInUrl: keywordCountInUrl,
firstParagraph: findKeywordInFirstParagraph,
metaDescriptionKeyword: metaDescriptionKeyword,
pageTitleWidth: pageTitleWidth,
wordComplexity: wordComplexity,
getParagraphLength: getParagraphLength,
countSentencesFromText: countSentencesFromText,
countSentencesFromDescription: countSentencesFromDescription,
getSubheadingTextLengths: getSubheadingTextLengths,
findTransitionWords: findTransitionWords,
passiveVoice: passiveVoice,
getSentenceBeginnings: getSentenceBeginnings,
relevantWords: relevantWords,
readingTime: readingTime,
getTopicDensity: getTopicDensity,
topicCount: topicCount,
sentences,
keyphraseDistribution: keyphraseDistribution,
morphology: morphology,
functionWordsInKeyphrase: functionWordsInKeyphrase,
h1s: h1s,
};
this._data = {};
this.customResearches = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q58681
|
areEqual
|
validation
|
function areEqual( urlA, urlB ) {
// Make sure we are comparing URLs without query arguments and hashes.
urlA = removeQueryArgs( removeHash( urlA ) );
urlB = removeQueryArgs( removeHash( urlB ) );
return addTrailingSlash( urlA ) === addTrailingSlash( urlB );
}
|
javascript
|
{
"resource": ""
}
|
q58682
|
isInternalLink
|
validation
|
function isInternalLink( url, host ) {
const parsedUrl = urlMethods.parse( url, false, true );
// Check if the URL starts with a single slash.
if ( url.indexOf( "//" ) === -1 && url.indexOf( "/" ) === 0 ) {
return true;
}
// Check if the URL starts with a # indicating a fragment.
if ( url.indexOf( "#" ) === 0 ) {
return false;
}
// No host indicates an internal link.
if ( ! parsedUrl.host ) {
return true;
}
return parsedUrl.host === host;
}
|
javascript
|
{
"resource": ""
}
|
q58683
|
validation
|
function( word, locale ) {
var numberOfSyllables = 0;
var vowelRegex = new RegExp( "[^" + syllableMatchers( locale ).vowels + "]", "ig" );
var foundVowels = word.split( vowelRegex );
var filteredWords = filter( foundVowels, function( vowel ) {
return vowel !== "";
} );
numberOfSyllables += filteredWords.length;
return numberOfSyllables;
}
|
javascript
|
{
"resource": ""
}
|
|
q58684
|
validation
|
function( word, locale ) {
var fullWordDeviations = syllableMatchers( locale ).deviations.words.full;
var deviation = find( fullWordDeviations, function( fullWordDeviation ) {
return fullWordDeviation.word === word;
} );
if ( ! isUndefined( deviation ) ) {
return deviation.syllables;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q58685
|
createDeviationFragments
|
validation
|
function createDeviationFragments( syllableConfig ) {
var deviationFragments = [];
var deviations = syllableConfig.deviations;
if ( ! isUndefined( deviations.words ) && ! isUndefined( deviations.words.fragments ) ) {
deviationFragments = flatMap( deviations.words.fragments, function( fragments, fragmentLocation ) {
return map( fragments, function( fragment ) {
fragment.location = fragmentLocation;
return new DeviationFragment( fragment );
} );
} );
}
return deviationFragments;
}
|
javascript
|
{
"resource": ""
}
|
q58686
|
validation
|
function( word, locale ) {
var deviationFragments = createDeviationFragmentsMemoized( syllableMatchers( locale ) );
var remainingParts = word;
var syllableCount = 0;
forEach( deviationFragments, function( deviationFragment ) {
if ( deviationFragment.occursIn( remainingParts ) ) {
remainingParts = deviationFragment.removeFrom( remainingParts );
syllableCount += deviationFragment.getSyllables();
}
} );
return { word: remainingParts, syllableCount: syllableCount };
}
|
javascript
|
{
"resource": ""
}
|
|
q58687
|
validation
|
function( word, locale ) {
var syllableCount = 0;
syllableCount += countVowelGroups( word, locale );
syllableCount += countVowelDeviations( word, locale );
return syllableCount;
}
|
javascript
|
{
"resource": ""
}
|
|
q58688
|
validation
|
function( word, locale ) {
var syllableCount = 0;
var fullWordExclusion = countFullWordDeviations( word, locale );
if ( fullWordExclusion !== 0 ) {
return fullWordExclusion;
}
var partialExclusions = countPartialWordDeviations( word, locale );
word = partialExclusions.word;
syllableCount += partialExclusions.syllableCount;
syllableCount += countUsingVowels( word, locale );
return syllableCount;
}
|
javascript
|
{
"resource": ""
}
|
|
q58689
|
validation
|
function( text, locale ) {
text = text.toLocaleLowerCase();
var words = getWords( text );
var syllableCounts = map( words, function( word ) {
return countSyllablesInWord( word, locale );
} );
return sum( syllableCounts );
}
|
javascript
|
{
"resource": ""
}
|
|
q58690
|
validation
|
function( array, language ) {
if ( isUndefined( language ) || language === "" ) {
language = "en";
}
const functionWords = get( getFunctionWords, [ language ], [] );
if ( array.length > 1 ) {
const arrayFiltered = filter( array, function( word ) {
return ( ! includes( functionWords.all, word.trim().toLocaleLowerCase() ) );
} );
if ( arrayFiltered.length > 0 ) {
return arrayFiltered;
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
|
q58691
|
validation
|
function( keyphrase, synonyms, language = "en", morphologyData ) {
const synonymsSplit = parseSynonyms( synonyms );
const keyphraseForms = buildForms( keyphrase, language, morphologyData );
const synonymsForms = synonymsSplit.map( synonym => buildForms( synonym, language, morphologyData ) );
return {
keyphraseForms: keyphraseForms,
synonymsForms: synonymsForms,
};
}
|
javascript
|
{
"resource": ""
}
|
|
q58692
|
collectForms
|
validation
|
function collectForms( keyphrase, synonyms, language = "en", morphologyData ) {
const collectFormsWithMorphologyData = primeMorphologyData( morphologyData );
return collectFormsWithMorphologyData( keyphrase, synonyms, language );
}
|
javascript
|
{
"resource": ""
}
|
q58693
|
research
|
validation
|
function research( paper, researcher ) {
const language = getLanguage( paper.getLocale() );
const morphologyData = get( researcher.getData( "morphology" ), [ language ], false );
return collectForms( paper.getKeyword(), paper.getSynonyms(), language, morphologyData );
}
|
javascript
|
{
"resource": ""
}
|
q58694
|
InvalidTypeError
|
validation
|
function InvalidTypeError( message ) {
Error.captureStackTrace( this, this.constructor );
this.name = this.constructor.name;
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q58695
|
getRegexFromDoubleArray
|
validation
|
function getRegexFromDoubleArray( twoPartTransitionWords ) {
const cacheKey = flattenDeep( twoPartTransitionWords ).join( "" );
if ( regexFromDoubleArrayCacheKey !== cacheKey || regexFromDoubleArray === null ) {
regexFromDoubleArrayCacheKey = cacheKey;
regexFromDoubleArray = createRegexFromDoubleArray( twoPartTransitionWords );
}
return regexFromDoubleArray;
}
|
javascript
|
{
"resource": ""
}
|
q58696
|
validation
|
function( sentence, twoPartTransitionWords ) {
sentence = normalizeSingleQuotes( sentence );
const twoPartTransitionWordsRegex = getRegexFromDoubleArray( twoPartTransitionWords );
return sentence.match( twoPartTransitionWordsRegex );
}
|
javascript
|
{
"resource": ""
}
|
|
q58697
|
validation
|
function( sentence, transitionWords ) {
sentence = normalizeSingleQuotes( sentence );
return transitionWords.filter( word => matchWordInSentence( word, sentence ) );
}
|
javascript
|
{
"resource": ""
}
|
|
q58698
|
validation
|
function( sentences, transitionWords ) {
const results = [];
sentences.forEach( sentence => {
const twoPartMatches = matchTwoPartTransitionWords( sentence, transitionWords.twoPartTransitionWords() );
if ( twoPartMatches !== null ) {
results.push( {
sentence: sentence,
transitionWords: twoPartMatches,
} );
return;
}
const transitionWordMatches = matchTransitionWords( sentence, transitionWords.transitionWords );
if ( transitionWordMatches.length !== 0 ) {
results.push( {
sentence: sentence,
transitionWords: transitionWordMatches,
} );
return;
}
} );
return results;
}
|
javascript
|
{
"resource": ""
}
|
|
q58699
|
getIndicesOfWords
|
validation
|
function getIndicesOfWords( text ) {
const indices = [];
const words = getWords( text );
let startSearchFrom = 0;
words.forEach( function( word ) {
const currentIndex = text.indexOf( word, startSearchFrom );
indices.push( currentIndex );
startSearchFrom = currentIndex + word.length;
} );
return indices;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.