_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q58200
|
parseAsElement
|
validation
|
function parseAsElement( node, _parsed ) {
// Attempt to convert string element into DOM node. If invalid, this will
// return a string, not window.Element
const element = createElementFromString( node );
if ( element instanceof window.Element ) {
// Recursing will trigger the DOM strategy
return _recurse( element, _parsed );
}
return _parsed;
}
|
javascript
|
{
"resource": ""
}
|
q58201
|
isDefaultOrNullQueryValue
|
validation
|
function isDefaultOrNullQueryValue( value, key ) {
return value === undefined || value === null || DEFAULT_THEME_QUERY[ key ] === value;
}
|
javascript
|
{
"resource": ""
}
|
q58202
|
settings
|
validation
|
function settings( state = {}, action ) {
switch ( action.type ) {
case WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST_FAILURE:
case WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_CAMPAIGN_DEFAULTS_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT_SUCCESS:
return Object.assign( {}, state, action.settings );
case WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST_SUCCESS:
const data = { mailchimp_lists: action.lists };
const listKeys = keys( action.lists );
if ( ! state.mailchimp_list && listKeys.length > 0 ) {
// Just pick first that will be shown to the user in the dropdown
// We are setting mailchimp_list just in case user likes it and clicks
// Continue without actually sellecting something.
data.mailchimp_list = listKeys[ 0 ];
}
return Object.assign( {}, state, data );
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58203
|
settingsRequest
|
validation
|
function settingsRequest( state = false, { type } ) {
switch ( type ) {
case WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST:
case WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST_FAILURE:
return WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST === type;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58204
|
settingsRequestError
|
validation
|
function settingsRequestError( state = false, action ) {
switch ( action.type ) {
case WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST_FAILURE:
const error =
WOOCOMMERCE_MAILCHIMP_SETTINGS_REQUEST_FAILURE === action.type ? action.error : false;
return error;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58205
|
syncStatus
|
validation
|
function syncStatus( state = {}, action ) {
switch ( action.type ) {
case WOOCOMMERCE_MAILCHIMP_SYNC_STATUS_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_RESYNC_REQUEST_SUCCESS:
return Object.assign( {}, action.syncStatus );
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58206
|
syncStatusRequest
|
validation
|
function syncStatusRequest( state = false, { type } ) {
switch ( type ) {
case WOOCOMMERCE_MAILCHIMP_SYNC_STATUS_REQUEST:
case WOOCOMMERCE_MAILCHIMP_SYNC_STATUS_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_SYNC_STATUS_REQUEST_FAILURE:
return WOOCOMMERCE_MAILCHIMP_SYNC_STATUS_REQUEST === type;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58207
|
resyncRequest
|
validation
|
function resyncRequest( state = false, { type } ) {
switch ( type ) {
case WOOCOMMERCE_MAILCHIMP_RESYNC_REQUEST:
case WOOCOMMERCE_MAILCHIMP_RESYNC_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_RESYNC_REQUEST_FAILURE:
return WOOCOMMERCE_MAILCHIMP_RESYNC_REQUEST === type;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58208
|
apiKeySubmit
|
validation
|
function apiKeySubmit( state = false, { type } ) {
switch ( type ) {
case WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT:
case WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT_FAILURE:
return WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT === type;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58209
|
apiKeySubmitError
|
validation
|
function apiKeySubmitError( state = false, action ) {
switch ( action.type ) {
case WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT_FAILURE:
const error =
WOOCOMMERCE_MAILCHIMP_API_KEY_SUBMIT_FAILURE === action.type ? action.error : false;
return error;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58210
|
storeInfoSubmit
|
validation
|
function storeInfoSubmit( state = false, { type } ) {
switch ( type ) {
case WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT:
case WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT_FAILURE:
return WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT === type;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58211
|
storeInfoSubmitError
|
validation
|
function storeInfoSubmitError( state = false, action ) {
switch ( action.type ) {
case WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT_FAILURE:
const error =
WOOCOMMERCE_MAILCHIMP_STORE_INFO_SUBMIT_FAILURE === action.type ? action.error : false;
return error;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58212
|
listsRequest
|
validation
|
function listsRequest( state = false, { type } ) {
switch ( type ) {
case WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST:
case WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST_FAILURE:
return WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST === type;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58213
|
listsRequestError
|
validation
|
function listsRequestError( state = false, action ) {
switch ( action.type ) {
case WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST_FAILURE:
const error =
WOOCOMMERCE_MAILCHIMP_LISTS_REQUEST_FAILURE === action.type ? action.error : false;
return error;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58214
|
newsletterSettingsSubmit
|
validation
|
function newsletterSettingsSubmit( state = false, { type } ) {
switch ( type ) {
case WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT:
case WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT_FAILURE:
return WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT === type;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58215
|
newsletterSettingsSubmitError
|
validation
|
function newsletterSettingsSubmitError( state = false, action ) {
switch ( action.type ) {
case WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT_SUCCESS:
case WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT_FAILURE:
const error =
WOOCOMMERCE_MAILCHIMP_NEWSLETTER_SETTINGS_SUBMIT_FAILURE === action.type
? action.error
: false;
return error;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q58216
|
deleteInvites
|
validation
|
function deleteInvites( siteInvites, invitesToDelete ) {
return siteInvites.filter( siteInvite => ! includes( invitesToDelete, siteInvite.key ) );
}
|
javascript
|
{
"resource": ""
}
|
q58217
|
StatsDataLocalList
|
validation
|
function StatsDataLocalList( options ) {
if ( ! ( this instanceof StatsDataLocalList ) ) {
return new StatsDataLocalList( options );
}
if ( 'string' !== typeof options.localStoreKey ) {
throw new TypeError( 'a options.localStoreKey must be passed in' );
}
debug( 'creating new local list' );
this.localStoreKey = options.localStoreKey;
this.limit = options.limit || 10;
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58218
|
updatedAction
|
validation
|
function updatedAction( siteId, originatingAction, successAction, sentData ) {
return ( dispatch, getState, { data: receivedData } ) => {
dispatch( productUpdated( siteId, receivedData, originatingAction ) );
const props = { sentData, receivedData };
dispatchWithProps( dispatch, getState, successAction, props );
};
}
|
javascript
|
{
"resource": ""
}
|
q58219
|
getPurchasesBySite
|
validation
|
function getPurchasesBySite( purchases, sites ) {
return purchases
.reduce( ( result, currentValue ) => {
const site = find( result, { id: currentValue.siteId } );
if ( site ) {
site.purchases = site.purchases.concat( currentValue );
} else {
const siteObject = find( sites, { ID: currentValue.siteId } );
result = result.concat( {
id: currentValue.siteId,
name: currentValue.siteName,
/* if the purchase is attached to a deleted site,
* there will be no site with this ID in `sites`, so
* we fall back on the domain. */
slug: siteObject ? siteObject.slug : currentValue.domain,
isDomainOnly: siteObject ? siteObject.options.is_domain_only : false,
title: currentValue.siteName || currentValue.domain || '',
purchases: [ currentValue ],
domain: siteObject ? siteObject.domain : currentValue.domain,
} );
}
return result;
}, [] )
.sort( ( a, b ) => ( a.title.toLowerCase() > b.title.toLowerCase() ? 1 : -1 ) );
}
|
javascript
|
{
"resource": ""
}
|
q58220
|
handleRenewNowClick
|
validation
|
function handleRenewNowClick( purchase, siteSlug ) {
const renewItem = cartItems.getRenewalItemFromProduct( purchase, {
domain: purchase.meta,
} );
const renewItems = [ renewItem ];
// Track the renew now submit.
analytics.tracks.recordEvent( 'calypso_purchases_renew_now_click', {
product_slug: purchase.productSlug,
} );
addItems( renewItems );
page( '/checkout/' + siteSlug );
}
|
javascript
|
{
"resource": ""
}
|
q58221
|
isCancelable
|
validation
|
function isCancelable( purchase ) {
if ( isIncludedWithPlan( purchase ) ) {
return false;
}
if ( isPendingTransfer( purchase ) ) {
return false;
}
if ( isExpired( purchase ) ) {
return false;
}
if ( isRefundable( purchase ) ) {
return true;
}
return purchase.canDisableAutoRenew;
}
|
javascript
|
{
"resource": ""
}
|
q58222
|
maybeWithinRefundPeriod
|
validation
|
function maybeWithinRefundPeriod( purchase ) {
if ( isRefundable( purchase ) ) {
return true;
}
// This looks at how much time has elapsed since the subscription date,
// which should be relatively reliable for new subscription refunds, but
// not renewals. To be completely accurate, this would need to look at the
// transaction date instead, but by definition this function needs to work
// in scenarios where we don't know exactly which transaction needs to be
// refunded.
// Another source of uncertainty here is that it relies on the user's
// clock, which might not be accurate.
return (
'undefined' !== typeof purchase.subscribedDate &&
'undefined' !== typeof purchase.refundPeriodInDays &&
moment().diff( moment( purchase.subscribedDate ), 'days' ) <= purchase.refundPeriodInDays
);
}
|
javascript
|
{
"resource": ""
}
|
q58223
|
isRemovable
|
validation
|
function isRemovable( purchase ) {
if ( isIncludedWithPlan( purchase ) ) {
return false;
}
if ( isConciergeSession( purchase ) ) {
return false;
}
return (
isJetpackPlan( purchase ) ||
isExpiring( purchase ) ||
isExpired( purchase ) ||
( isDomainTransfer( purchase ) &&
! isRefundable( purchase ) &&
isPurchaseCancelable( purchase ) )
);
}
|
javascript
|
{
"resource": ""
}
|
q58224
|
paymentLogoType
|
validation
|
function paymentLogoType( purchase ) {
if ( isPaidWithCreditCard( purchase ) ) {
return purchase.payment.creditCard.type;
}
if ( isPaidWithPayPalDirect( purchase ) ) {
return 'placeholder';
}
return purchase.payment.type || null;
}
|
javascript
|
{
"resource": ""
}
|
q58225
|
cssNameFromFilename
|
validation
|
function cssNameFromFilename( name ) {
if ( name ) {
const [ cssChunkFilename, chunkQueryString ] = name.split( '?', 2 );
return cssChunkFilename.replace(
/\.js$/i,
'.css' + ( chunkQueryString ? `?${ chunkQueryString }` : '' )
);
}
}
|
javascript
|
{
"resource": ""
}
|
q58226
|
verifyHTML
|
validation
|
function verifyHTML( caption ) {
if ( ! caption || ( caption.indexOf( '<' ) === -1 && caption.indexOf( '>' ) === -1 ) ) {
return caption;
}
if ( ! serializer ) {
serializer = new tinymce.html.Serializer( {}, editor.schema );
}
return serializer.serialize( editor.parser.parse( caption, { forced_root_block: false } ) );
}
|
javascript
|
{
"resource": ""
}
|
q58227
|
loadCSS
|
validation
|
function loadCSS( cssUrl, currentLink ) {
return new Promise( resolve => {
const link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = cssUrl;
if ( 'onload' in link ) {
link.onload = () => {
link.onload = null;
resolve( link );
};
} else {
// just wait 500ms if the browser doesn't support link.onload
// https://pie.gd/test/script-link-events/
// https://github.com/ariya/phantomjs/issues/12332
setTimeout( () => resolve( link ), 500 );
}
document.head.insertBefore( link, currentLink ? currentLink.nextSibling : null );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58228
|
overwriteExistingPurchases
|
validation
|
function overwriteExistingPurchases( existingPurchases, newPurchases ) {
let purchases = newPurchases;
existingPurchases.forEach( purchase => {
if ( ! find( purchases, { ID: purchase.ID } ) ) {
purchases = purchases.concat( purchase );
}
} );
return purchases;
}
|
javascript
|
{
"resource": ""
}
|
q58229
|
removeMissingPurchasesByPredicate
|
validation
|
function removeMissingPurchasesByPredicate( existingPurchases, newPurchases, predicate ) {
return existingPurchases.filter( purchase => {
if ( matches( predicate )( purchase ) && find( newPurchases, { ID: purchase.ID } ) ) {
// this purchase is present in the new array
return true;
}
if ( ! matches( predicate )( purchase ) ) {
// only overwrite remove purchases that match the predicate
return true;
}
// the purchase doesn't match the predicate or is missing from the array of new purchases
return false;
} );
}
|
javascript
|
{
"resource": ""
}
|
q58230
|
UndocumentedSite
|
validation
|
function UndocumentedSite( id, wpcom ) {
debug( 'UndocumentedSite', id );
if ( ! ( this instanceof UndocumentedSite ) ) {
return new UndocumentedSite( id, wpcom );
}
this.wpcom = wpcom;
this._id = id;
}
|
javascript
|
{
"resource": ""
}
|
q58231
|
addOrEditProduct
|
validation
|
function addOrEditProduct( list = [], newProduct ) {
let found = 0;
const products = list.map( product => {
if ( product.ID === newProduct.ID ) {
found = 1;
return newProduct;
}
return product;
} );
if ( ! found ) {
return [ newProduct, ...products ];
}
return products;
}
|
javascript
|
{
"resource": ""
}
|
q58232
|
createSitesComponent
|
validation
|
function createSitesComponent( context ) {
const contextPath = sectionify( context.path );
// This path sets the URL to be visited once a site is selected
const basePath = contextPath === '/sites' ? '/stats' : contextPath;
analytics.pageView.record( contextPath, sitesPageTitleForAnalytics );
return (
<SitesComponent
siteBasePath={ basePath }
getSiteSelectionHeaderText={ context.getSiteSelectionHeaderText }
/>
);
}
|
javascript
|
{
"resource": ""
}
|
q58233
|
updateReceiptState
|
validation
|
function updateReceiptState( state, receiptId, attributes ) {
return Object.assign( {}, state, {
[ receiptId ]: Object.assign( {}, initialReceiptState, state[ receiptId ], attributes ),
} );
}
|
javascript
|
{
"resource": ""
}
|
q58234
|
isTrackingPixel
|
validation
|
function isTrackingPixel( image ) {
if ( ! image || ! image.src ) {
return false;
}
const edgeLength = image.height + image.width;
return edgeLength === 1 || edgeLength === 2;
}
|
javascript
|
{
"resource": ""
}
|
q58235
|
isCandidateForContentImage
|
validation
|
function isCandidateForContentImage( image ) {
if ( ! image || ! image.getAttribute( 'src' ) ) {
return false;
}
const ineligibleCandidateUrlParts = [ 'gravatar.com', '/wpcom-smileys/' ];
const imageUrl = image.getAttribute( 'src' );
const imageShouldBeExcludedFromCandidacy = some( ineligibleCandidateUrlParts, urlPart =>
includes( imageUrl.toLowerCase(), urlPart )
);
return ! ( isTrackingPixel( image ) || imageShouldBeExcludedFromCandidacy );
}
|
javascript
|
{
"resource": ""
}
|
q58236
|
ready
|
validation
|
function ready() {
const notes = getAllNotes( store.getState() );
const timestamps = notes
.map( property( 'timestamp' ) )
.map( timestamp => Date.parse( timestamp ) / 1000 );
let newNoteCount = timestamps.filter( time => time > this.lastSeenTime ).length;
if ( ! this.firstRender && this.lastSeenTime === 0 ) {
newNoteCount = 0;
}
const latestType = get( notes.slice( -1 )[ 0 ], 'type', null );
store.dispatch( { type: 'APP_RENDER_NOTES', newNoteCount, latestType } );
this.hasNewNoteData = false;
this.firstRender = false;
}
|
javascript
|
{
"resource": ""
}
|
q58237
|
updateLastSeenTime
|
validation
|
function updateLastSeenTime( proposedTime, fromStorage ) {
let fromNote = false;
let mostRecentNoteTime = 0;
// Make sure we aren't getting milliseconds
// The check time is Aug 8, 2005 in ms
if ( proposedTime > 1123473600000 ) {
proposedTime = proposedTime / 1000;
}
debug( 'updateLastSeenTime 0', {
proposedTime: proposedTime,
fromStorage: fromStorage,
lastSeenTime: this.lastSeenTime,
} );
// Event was triggered by another tab's localStorage.setItem; ignore localStorage and remote.
if ( fromStorage ) {
if ( proposedTime <= this.lastSeenTime ) {
return false;
}
this.lastSeenTime = proposedTime;
return true;
}
const notes = getAllNotes( store.getState() );
if ( notes.length ) {
mostRecentNoteTime = Date.parse( notes[ 0 ].timestamp ) / 1000;
}
debug( 'updateLastSeenTime 1', {
proposedTime: proposedTime,
showing: this.showing,
visible: this.visible,
lastSeenTime: this.lastSeenTime,
mostRecentNoteTime: mostRecentNoteTime,
} );
// Advance proposedTime to the latest visible note time.
if ( this.isShowing && this.isVisible && mostRecentNoteTime > proposedTime ) {
proposedTime = mostRecentNoteTime;
fromNote = true;
}
debug( 'updateLastSeenTime 2', {
proposedTime: proposedTime,
fromNote: fromNote,
oldNews: proposedTime <= this.lastSeenTime,
} );
// Ignore old news.
if ( proposedTime <= this.lastSeenTime ) {
return false;
}
this.lastSeenTime = proposedTime;
try {
localStorage.setItem( 'notesLastMarkedSeen', this.lastSeenTime );
} catch ( e ) {}
// Update the database only if an unseen note has become visible.
if ( fromNote ) {
debug( 'updateLastSeenTime 3', this.lastSeenTime );
sendLastSeenTime( this.lastSeenTime );
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q58238
|
accessibleFocus
|
validation
|
function accessibleFocus() {
document.addEventListener( 'keydown', function( event ) {
if ( keyboardNavigation ) {
return;
}
if ( keyboardNavigationKeycodes.indexOf( event.keyCode ) !== -1 ) {
keyboardNavigation = true;
document.documentElement.classList.add( 'accessible-focus' );
}
} );
document.addEventListener( 'mouseup', function() {
if ( ! keyboardNavigation ) {
return;
}
keyboardNavigation = false;
document.documentElement.classList.remove( 'accessible-focus' );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58239
|
filterNoticesBy
|
validation
|
function filterNoticesBy( site, pluginSlug, log ) {
if ( ! site && ! pluginSlug ) {
return true;
}
if ( isSameSiteNotice( site, log ) && isSamePluginNotice( pluginSlug, log ) ) {
return true;
} else if ( ! pluginSlug && isSameSiteNotice( site, log ) ) {
return true;
} else if ( ! site && isSamePluginNotice( pluginSlug, log ) ) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q58240
|
isInViewportRange
|
validation
|
function isInViewportRange( elementStart, elementEnd ) {
let viewportStart = window.scrollY,
viewportEnd = document.documentElement.clientHeight + window.scrollY;
return elementStart > viewportStart && elementEnd < viewportEnd;
}
|
javascript
|
{
"resource": ""
}
|
q58241
|
scrollIntoViewport
|
validation
|
function scrollIntoViewport( element ) {
const elementStartY = recursivelyWalkAndSum( element, 'offsetTop', 'offsetParent' ),
elementEndY = elementStartY + element.offsetHeight;
if ( isInViewportRange( elementStartY, elementEndY ) ) {
return;
}
try {
window.scroll( {
top: elementStartY,
left: 0,
behavior: 'smooth',
} );
} catch ( e ) {
window.scrollTo( 0, elementStartY );
}
}
|
javascript
|
{
"resource": ""
}
|
q58242
|
setup
|
validation
|
function setup() {
var build = null,
errors = '',
rootdir = path.resolve( __dirname, '..', '..' );
function spawnMake() {
debug( 'spawning %o', 'npm run build-css' );
build = spawn( 'npm', [ 'run', 'build-css' ], {
shell: true,
cwd: rootdir,
stdio: [ 'ignore', 'pipe', 'pipe' ],
} );
errors = '';
build.once( 'exit', onexit );
build.stdout.setEncoding( 'utf8' );
build.stdout.on( 'data', onstdout );
build.stderr.on( 'data', onstderr );
}
function onstdout( d ) {
debug( 'stdout %o', d.trim() );
}
function onexit() {
build.stderr.removeListener( 'data', onstderr );
build.stdout.removeListener( 'data', onstdout );
build = null;
}
function onstderr( stderr ) {
process.stderr.write( stderr.toString( 'utf8' ) );
errors += stderr.toString( 'utf8' );
}
return function( req, res, next ) {
if ( ! build ) {
spawnMake();
}
build.once( 'exit', function( code ) {
if ( 0 === code ) {
// `make` success
next();
} else {
// `make` failed
res.send( '<pre>`npm run build-css` failed \n\n' + errors + '</pre>' );
}
} );
};
}
|
javascript
|
{
"resource": ""
}
|
q58243
|
parseCaption
|
validation
|
function parseCaption( node, _parsed ) {
// Pull named attributes
if ( node.attrs && node.attrs.named ) {
// Caption align is suffixed with "align"
if ( REGEXP_CAPTION_ALIGN.test( node.attrs.named.align ) ) {
_parsed.appearance.align = node.attrs.named.align.match( REGEXP_CAPTION_ALIGN )[ 1 ];
}
// Caption ID is suffixed with "attachment_"
if ( REGEXP_CAPTION_ID.test( node.attrs.named.id ) ) {
_parsed.media.ID = parseInt( node.attrs.named.id.match( REGEXP_CAPTION_ID )[ 1 ], 10 );
}
// Extract dimensions
if ( _parsed.media.width && isFinite( node.attrs.named.width ) ) {
_parsed.media.width = parseInt( node.attrs.named.width, 10 );
}
}
// If shortcode contains no content, we're finished at this point
if ( ! node.content ) {
return _parsed;
}
// Extract shortcode content, including caption text as sibling
// adjacent to the image itself.
const img = node.content.match( REGEXP_CAPTION_CONTENT );
if ( img && img[ 2 ] ) {
_parsed.media.caption = img[ 2 ].trim();
}
// If content contains image in addition to caption text, continue
// to parse the image
if ( img ) {
return _recurse( img[ 1 ], _parsed );
}
return _parsed;
}
|
javascript
|
{
"resource": ""
}
|
q58244
|
KeyboardShortcuts
|
validation
|
function KeyboardShortcuts( keyBindings ) {
if ( ! ( this instanceof KeyboardShortcuts ) ) {
return new KeyboardShortcuts( keyBindings );
}
// the last key and when it was pressed
this.lastKey = undefined;
this.lastKeyTime = undefined;
// the time limit for determining whether two keys in order represent a key sequence
this.timeLimit = 2000;
// save a copy of the bound last-key-pressed handler so it can be removed later
this.boundKeyHandler = this.handleKeyPress.bind( this );
// is the notifications panel open? If so we don't fire off key-handlers
this.isNotificationsOpen = false;
// bind the shortcuts if this is a browser environment
if ( typeof window !== 'undefined' ) {
keymaster.filter = ignoreDefaultAndContentEditableFilter;
this.bindShortcuts( keyBindings );
}
}
|
javascript
|
{
"resource": ""
}
|
q58245
|
validation
|
function() {
return flatten(
compact(
map( this._flow.steps, function( step ) {
return steps[ step ].providesDependencies;
} )
)
).concat( this._flow.providesDependenciesInQuery );
}
|
javascript
|
{
"resource": ""
}
|
|
q58246
|
isPendingSyncStart
|
validation
|
function isPendingSyncStart( state, siteId ) {
const syncStatus = getSyncStatus( state, siteId );
const fullSyncRequest = getFullSyncRequest( state, siteId );
// Is the sync scheduled and awaiting cron?
const isScheduled = get( syncStatus, 'is_scheduled' );
if ( isScheduled ) {
return true;
}
// Have we requested a full sync from Calypso?
const requestingFullSync =
get( fullSyncRequest, 'isRequesting' ) || get( fullSyncRequest, 'scheduled' );
if ( ! requestingFullSync ) {
return false;
}
// If we have requested a full sync, is that request newer than the last time we received sync status?
const lastRequested = get( fullSyncRequest, 'lastRequested' );
const lastSuccessfulStatus = get( syncStatus, 'lastSuccessfulStatus' );
if ( ! lastSuccessfulStatus ) {
return true;
}
return parseInt( lastRequested, 10 ) > parseInt( lastSuccessfulStatus, 10 );
}
|
javascript
|
{
"resource": ""
}
|
q58247
|
isFullSyncing
|
validation
|
function isFullSyncing( state, siteId ) {
const syncStatus = getSyncStatus( state, siteId );
if ( ! syncStatus ) {
return false;
}
const isStarted = get( syncStatus, 'started' );
const isFinished = get( syncStatus, 'finished' );
return isStarted && ! isFinished;
}
|
javascript
|
{
"resource": ""
}
|
q58248
|
getSyncProgressPercentage
|
validation
|
function getSyncProgressPercentage( state, siteId ) {
const syncStatus = getSyncStatus( state, siteId ),
queued = get( syncStatus, 'queue' ),
sent = get( syncStatus, 'sent' ),
total = get( syncStatus, 'total' ),
queuedMultiplier = 0.1,
sentMultiplier = 0.9;
if ( isPendingSyncStart( state, siteId ) || ! queued || ! sent || ! total ) {
return 0;
}
const countQueued = reduce(
queued,
( sum, value ) => {
return ( sum += value );
},
0
);
const countSent = reduce(
sent,
( sum, value ) => {
return ( sum += value );
},
0
);
const countTotal = reduce(
total,
( sum, value ) => {
return ( sum += value );
},
0
);
const percentQueued = ( countQueued / countTotal ) * queuedMultiplier * 100;
const percentSent = ( countSent / countTotal ) * sentMultiplier * 100;
return Math.ceil( percentQueued + percentSent );
}
|
javascript
|
{
"resource": ""
}
|
q58249
|
setupQuoraGlobal
|
validation
|
function setupQuoraGlobal() {
if ( window.qp ) {
return;
}
const quoraPixel = ( window.qp = function() {
quoraPixel.qp
? quoraPixel.qp.apply( quoraPixel, arguments )
: quoraPixel.queue.push( arguments );
} );
quoraPixel.queue = [];
}
|
javascript
|
{
"resource": ""
}
|
q58250
|
recordProduct
|
validation
|
function recordProduct( product, orderId ) {
if ( ! isAdTrackingAllowed() ) {
debug( 'recordProduct: [Skipping] ad tracking is not allowed' );
return;
}
if ( TRACKING_STATE_VALUES.LOADED !== trackingState ) {
loadTrackingScripts( recordProduct.bind( null, product, orderId ) );
return;
}
const isJetpackPlan = productsValues.isJetpackPlan( product );
if ( isJetpackPlan ) {
debug( 'Recording Jetpack purchase', product );
} else {
debug( 'Recording purchase', product );
}
const currentUser = user.get();
const userId = currentUser ? hashPii( currentUser.ID ) : 0;
try {
// Google Analytics
const item = {
currency: product.currency,
id: orderId,
name: product.product_slug,
price: product.cost,
sku: product.product_slug,
quantity: 1,
};
debug( 'recordProduct: ga ecommerce add item', item );
window.ga( 'ecommerce:addItem', item );
// Google AdWords
if ( isAdwordsEnabled ) {
if ( window.google_trackConversion ) {
let googleConversionId, googleConversionLabel;
if ( isJetpackPlan ) {
googleConversionId = ADWORDS_CONVERSION_ID_JETPACK;
googleConversionLabel = TRACKING_IDS.googleConversionLabelJetpack;
} else {
googleConversionId = ADWORDS_CONVERSION_ID;
googleConversionLabel = TRACKING_IDS.googleConversionLabel;
}
window.google_trackConversion( {
google_conversion_id: googleConversionId,
google_conversion_label: googleConversionLabel,
google_conversion_value: product.cost,
google_conversion_currency: product.currency,
google_custom_params: {
product_slug: product.product_slug,
user_id: userId,
order_id: orderId,
},
google_remarketing_only: false,
} );
}
}
} catch ( err ) {
debug( 'Unable to save purchase tracking data', err );
}
}
|
javascript
|
{
"resource": ""
}
|
q58251
|
recordOrderInQuantcast
|
validation
|
function recordOrderInQuantcast( cart, orderId, wpcomJetpackCartInfo ) {
if ( ! isAdTrackingAllowed() || ! isQuantcastEnabled ) {
return;
}
if ( wpcomJetpackCartInfo.containsWpcomProducts ) {
if ( null !== wpcomJetpackCartInfo.wpcomCostUSD ) {
// Note that all properties have to be strings or they won't get tracked
const params = {
qacct: TRACKING_IDS.quantcast,
labels:
'_fp.event.Purchase Confirmation,_fp.pcat.' +
wpcomJetpackCartInfo.wpcomProducts.map( product => product.product_slug ).join( ' ' ),
orderid: orderId.toString(),
revenue: wpcomJetpackCartInfo.wpcomCostUSD.toString(),
event: 'refresh',
};
debug( 'recordOrderInQuantcast: record WPCom purchase', params );
window._qevents.push( params );
} else {
debug(
`recordOrderInQuantcast: currency ${ cart.currency } not supported, dropping WPCom pixel`
);
}
}
if ( wpcomJetpackCartInfo.containsJetpackProducts ) {
if ( null !== wpcomJetpackCartInfo.jetpackCostUSD ) {
// Note that all properties have to be strings or they won't get tracked
const params = {
qacct: TRACKING_IDS.quantcast,
labels:
'_fp.event.Purchase Confirmation,_fp.pcat.' +
wpcomJetpackCartInfo.jetpackProducts.map( product => product.product_slug ).join( ' ' ),
orderid: orderId.toString(),
revenue: wpcomJetpackCartInfo.jetpackCostUSD.toString(),
event: 'refresh',
};
debug( 'recordOrderInQuantcast: record Jetpack purchase', params );
window._qevents.push( params );
} else {
debug(
`recordOrderInQuantcast: currency ${ cart.currency } not supported, dropping Jetpack pixel`
);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58252
|
recordOrderInFloodlight
|
validation
|
function recordOrderInFloodlight( cart, orderId, wpcomJetpackCartInfo ) {
if ( ! isAdTrackingAllowed() || ! isFloodlightEnabled ) {
return;
}
debug( 'recordOrderInFloodlight: record purchase' );
debug( 'recordOrderInFloodlight:' );
recordParamsInFloodlightGtag( {
value: cart.total_cost,
transaction_id: orderId,
u1: cart.total_cost,
u2: cart.products.map( product => product.product_name ).join( ', ' ),
u3: cart.currency,
send_to: 'DC-6355556/wpsal0/wpsale+transactions',
} );
// WPCom
if ( wpcomJetpackCartInfo.containsWpcomProducts ) {
debug( 'recordOrderInFloodlight: WPCom' );
recordParamsInFloodlightGtag( {
value: wpcomJetpackCartInfo.wpcomCost,
transaction_id: orderId,
u1: wpcomJetpackCartInfo.wpcomCost,
u2: wpcomJetpackCartInfo.wpcomProducts.map( product => product.product_name ).join( ', ' ),
u3: cart.currency,
send_to: 'DC-6355556/wpsal0/purch0+transactions',
} );
}
// Jetpack
if ( wpcomJetpackCartInfo.containsJetpackProducts ) {
debug( 'recordOrderInFloodlight: Jetpack' );
recordParamsInFloodlightGtag( {
value: wpcomJetpackCartInfo.jetpackCost,
transaction_id: orderId,
u1: wpcomJetpackCartInfo.jetpackCost,
u2: wpcomJetpackCartInfo.jetpackProducts.map( product => product.product_name ).join( ', ' ),
u3: cart.currency,
send_to: 'DC-6355556/wpsal0/purch00+transactions',
} );
}
}
|
javascript
|
{
"resource": ""
}
|
q58253
|
recordOrderInBing
|
validation
|
function recordOrderInBing( cart, orderId, wpcomJetpackCartInfo ) {
// NOTE: `orderId` is not used at this time, but it could be useful in the near future.
if ( ! isAdTrackingAllowed() || ! isBingEnabled ) {
return;
}
if ( wpcomJetpackCartInfo.containsWpcomProducts ) {
if ( null !== wpcomJetpackCartInfo.wpcomCostUSD ) {
const params = {
ec: 'purchase',
gv: wpcomJetpackCartInfo.wpcomCostUSD,
};
debug( 'recordOrderInBing: record WPCom purchase', params );
window.uetq.push( params );
} else {
debug( `recordOrderInBing: currency ${ cart.currency } not supported, dropping WPCom pixel` );
}
}
if ( wpcomJetpackCartInfo.containsJetpackProducts ) {
if ( null !== wpcomJetpackCartInfo.jetpackCostUSD ) {
const params = {
ec: 'purchase',
gv: wpcomJetpackCartInfo.jetpackCostUSD,
// NOTE: `el` must be included only for jetpack plans.
el: 'jetpack',
};
debug( 'recordOrderInBing: record Jetpack purchase', params );
window.uetq.push( params );
} else {
debug(
`recordOrderInBing: currency ${ cart.currency } not supported, dropping Jetpack pixel`
);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58254
|
floodlightSessionId
|
validation
|
function floodlightSessionId() {
const cookies = cookie.parse( document.cookie );
const existingSessionId = cookies[ DCM_FLOODLIGHT_SESSION_COOKIE_NAME ];
if ( existingSessionId ) {
debug( 'Floodlight: Existing session: ' + existingSessionId );
return existingSessionId;
}
// Generate a 32-byte random session id
const newSessionId = uuid().replace( new RegExp( '-', 'g' ), '' );
debug( 'Floodlight: New session: ' + newSessionId );
return newSessionId;
}
|
javascript
|
{
"resource": ""
}
|
q58255
|
floodlightUserParams
|
validation
|
function floodlightUserParams() {
const params = {};
const currentUser = user.get();
if ( currentUser ) {
params.u4 = hashPii( currentUser.ID );
}
const anonymousUserId = tracksAnonymousUserId();
if ( anonymousUserId ) {
params.u5 = anonymousUserId;
}
return params;
}
|
javascript
|
{
"resource": ""
}
|
q58256
|
recordOrderInCriteo
|
validation
|
function recordOrderInCriteo( cart, orderId ) {
if ( ! isAdTrackingAllowed() || ! isCriteoEnabled ) {
return;
}
const params = [
'trackTransaction',
{
id: orderId,
currency: cart.currency,
item: cartToCriteoItems( cart ),
},
];
debug( 'recordOrderInCriteo:', params );
recordInCriteo( ...params );
}
|
javascript
|
{
"resource": ""
}
|
q58257
|
recordViewCheckoutInCriteo
|
validation
|
function recordViewCheckoutInCriteo( cart ) {
if ( ! isAdTrackingAllowed() || ! isCriteoEnabled ) {
return;
}
if ( cart.is_signup ) {
return;
}
// Note that unlike `recordOrderInCriteo` above, this doesn't include the order id
const params = [
'viewBasket',
{
currency: cart.currency,
item: cartToCriteoItems( cart ),
},
];
debug( 'recordViewCheckoutInCriteo:', params );
recordInCriteo( ...params );
}
|
javascript
|
{
"resource": ""
}
|
q58258
|
cartToCriteoItems
|
validation
|
function cartToCriteoItems( cart ) {
return cart.products.map( product => {
return {
id: product.product_id,
price: product.cost,
quantity: product.volume,
};
} );
}
|
javascript
|
{
"resource": ""
}
|
q58259
|
recordInCriteo
|
validation
|
function recordInCriteo( eventName, eventProps ) {
if ( ! isAdTrackingAllowed() || ! isCriteoEnabled ) {
debug( 'recordInCriteo: [Skipping] ad tracking is not allowed' );
return;
}
if ( TRACKING_STATE_VALUES.LOADED !== trackingState ) {
loadTrackingScripts( recordInCriteo.bind( null, eventName, eventProps ) );
return;
}
const events = [];
events.push( { event: 'setAccount', account: TRACKING_IDS.criteo } );
events.push( { event: 'setSiteType', type: criteoSiteType() } );
const normalizedHashedEmail = getNormalizedHashedUserEmail( user );
if ( normalizedHashedEmail ) {
events.push( { event: 'setEmail', email: [ normalizedHashedEmail ] } );
}
const conversionEvent = clone( eventProps );
conversionEvent.event = eventName;
events.push( conversionEvent );
// The deep clone is necessary because the Criteo script modifies the objects in the
// array which causes the console to display different data than is originally added
debug( 'recordInCriteo: ' + eventName, cloneDeep( events ) );
window.criteo_q.push( ...events );
}
|
javascript
|
{
"resource": ""
}
|
q58260
|
recordOrderInGoogleAnalytics
|
validation
|
function recordOrderInGoogleAnalytics( cart, orderId ) {
if ( ! isAdTrackingAllowed() ) {
debug( 'recordOrderInGoogleAnalytics: skipping as ad tracking is disallowed' );
return;
}
const transaction = {
id: orderId,
affiliation: 'WordPress.com',
revenue: cart.total_cost,
currency: cart.currency,
};
debug( 'recordOrderInGoogleAnalytics: ga ecommerce add transaction', transaction );
window.ga( 'ecommerce:addTransaction', transaction );
}
|
javascript
|
{
"resource": ""
}
|
q58261
|
initFacebook
|
validation
|
function initFacebook() {
if ( user.get() ) {
initFacebookAdvancedMatching();
} else {
window.fbq( 'init', TRACKING_IDS.facebookInit );
/*
* Also initialize the FB pixel for Jetpack.
* However, disable auto-config for this secondary pixel ID.
* See: <https://developers.facebook.com/docs/facebook-pixel/api-reference#automatic-configuration>
*/
window.fbq( 'set', 'autoConfig', false, TRACKING_IDS.facebookJetpackInit );
window.fbq( 'init', TRACKING_IDS.facebookJetpackInit );
}
}
|
javascript
|
{
"resource": ""
}
|
q58262
|
isServerSideRenderCompatible
|
validation
|
function isServerSideRenderCompatible( context ) {
return Boolean(
isSectionIsomorphic( context.store.getState() ) &&
! context.user && // logged out only
isDefaultLocale( context.lang ) &&
context.layout
);
}
|
javascript
|
{
"resource": ""
}
|
q58263
|
setTabIndexOnEditorIframe
|
validation
|
function setTabIndexOnEditorIframe( tabindex ) {
return function() {
// At this point, there's an iframe in the DOM with the id of `${editor.id}_ifr`.
// Can't find a way to get at it without hopping out to the DOM :/
const editorIframe = document.getElementById( `${ this.id }_ifr` );
if ( ! editorIframe ) {
return;
}
editorIframe.setAttribute( 'tabIndex', tabindex );
};
}
|
javascript
|
{
"resource": ""
}
|
q58264
|
cleanupRepliesCache
|
validation
|
function cleanupRepliesCache() {
const keysToRemove = [];
try {
for ( let i = 0; i < localStorage.length; i++ ) {
const storedReplyKey = localStorage.key( i );
// cleanup caches replies older than a day
if ( 'reply_' == localStorage.key( i ).substring( 0, 6 ) ) {
const storedReply = getItem( storedReplyKey );
if ( storedReply && Date.now() - storedReply[ 1 ] >= 24 * 60 * 60 * 1000 ) {
keysToRemove.push( storedReplyKey );
}
}
}
} catch ( e ) {
debug( 'couldnt cleanup cache' );
}
keysToRemove.forEach( function( key ) {
removeItem( key );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58265
|
parseGitDiffToPathArray
|
validation
|
function parseGitDiffToPathArray( command ) {
return execSync( command, { encoding: 'utf8' } )
.split( '\n' )
.map( name => name.trim() )
.filter( name => /(?:\.json|\.[jt]sx?|\.scss)$/.test( name ) );
}
|
javascript
|
{
"resource": ""
}
|
q58266
|
requestPosts
|
validation
|
function requestPosts( siteId, query = {} ) {
return dispatch => {
dispatch( {
type: POSTS_REQUEST,
siteId,
query,
} );
const source = siteId ? wpcom.site( siteId ) : wpcom.me();
return source
.postsList( { ...query } )
.then( ( { found, posts } ) => {
dispatch( receivePosts( posts ) );
dispatch( {
type: POSTS_REQUEST_SUCCESS,
siteId,
query,
found,
posts,
} );
} )
.catch( error => {
dispatch( {
type: POSTS_REQUEST_FAILURE,
siteId,
query,
error,
} );
} );
};
}
|
javascript
|
{
"resource": ""
}
|
q58267
|
normalizeApiAttributes
|
validation
|
function normalizeApiAttributes( attributes ) {
attributes = clone( attributes );
attributes = normalizeTermsForApi( attributes );
if ( attributes.author ) {
attributes.author = attributes.author.ID;
}
return attributes;
}
|
javascript
|
{
"resource": ""
}
|
q58268
|
isImageLargeEnoughForFeature
|
validation
|
function isImageLargeEnoughForFeature( image ) {
if ( ! image ) {
return false;
}
const imageIsTallEnough = 100 <= image.width;
const imageIsWideEnough = 75 <= image.height;
return imageIsTallEnough && imageIsWideEnough;
}
|
javascript
|
{
"resource": ""
}
|
q58269
|
replaceMarkers
|
validation
|
function replaceMarkers() {
const markers = $( '.wpview-marker' );
if ( ! markers.length ) {
return false;
}
markers.each( function( index, node ) {
let text = editor.dom.getAttrib( node, 'data-wpview-text' ),
type = editor.dom.getAttrib( node, 'data-wpview-type' );
editor.dom.replace(
editor.dom.createFragment(
'<div class="wpview-wrap" data-wpview-text="' +
text +
'" data-wpview-type="' +
type +
'">' +
'<p class="wpview-selection-before">\u00a0</p>' +
'<div class="wpview-body" contenteditable="false"></div>' +
'<p class="wpview-selection-after">\u00a0</p>' +
'</div>'
),
node
);
} );
return true;
}
|
javascript
|
{
"resource": ""
}
|
q58270
|
getParent
|
validation
|
function getParent( node, className ) {
while ( node && node.parentNode ) {
if (
node.className &&
( ' ' + node.className + ' ' ).indexOf( ' ' + className + ' ' ) !== -1
) {
return node;
}
node = node.parentNode;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q58271
|
deselect
|
validation
|
function deselect() {
let clipboard,
dom = editor.dom;
if ( selected ) {
clipboard = editor.dom.select( '.wpview-clipboard', selected )[ 0 ];
dom.unbind( clipboard );
dom.remove( clipboard );
dom.unbind( selected, 'beforedeactivate focusin focusout click mouseup', _stop );
dom.setAttrib( selected, 'data-mce-selected', null );
}
selected = null;
}
|
javascript
|
{
"resource": ""
}
|
q58272
|
deepRemoveUndefinedKeysFromObject
|
validation
|
function deepRemoveUndefinedKeysFromObject( obj ) {
for ( let key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
if ( _.isUndefined( obj[ key ] ) ) {
delete obj[ key ];
} else if ( _.isObject( obj[ key ] ) ) {
deepRemoveUndefinedKeysFromObject( obj[ key ] );
}
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q58273
|
processLibPhoneNumberMetadata
|
validation
|
function processLibPhoneNumberMetadata( libPhoneNumberData ) {
const data = {};
for ( let countryCode in libPhoneNumberData ) {
if ( libPhoneNumberData.hasOwnProperty( countryCode ) ) {
const countryCodeUpper = countryCode.toUpperCase();
const country = libPhoneNumberData[ countryCode ];
data[ countryCodeUpper ] = {
isoCode: countryCodeUpper,
dialCode: String(
country[ libPhoneNumberIndexes.COUNTRY_DIAL_CODE ] +
( country[ libPhoneNumberIndexes.REGION_AREA_CODE ] || '' )
),
countryDialCode: String( country[ libPhoneNumberIndexes.COUNTRY_DIAL_CODE ] ),
regionCode: country[ libPhoneNumberIndexes.REGION_AREA_CODE ] || '',
areaCodes: areaCodes[ countryCode ],
nationalPrefix: country[ libPhoneNumberIndexes.NATIONAL_PREFIX ],
patterns: ( country[ libPhoneNumberIndexes.NUMBER_FORMAT ] || [] ).map(
processNumberFormat
),
internationalPatterns: (
country[ libPhoneNumberIndexes.INTERNATIONAL_NUMBER_FORMAT ] || []
).map( processNumberFormat ),
priority: priorityData[ countryCodeUpper ],
};
}
}
const noPattern = _.filter( data, _.conforms( { patterns: patterns => patterns.length === 0 } ) );
_.forIn( noPattern, function( country ) {
country.patternRegion = (
_.maxBy( _.values( _.filter( data, { dialCode: country.dialCode } ) ), 'priority' ) || {}
).isoCode;
console.log(
'Info: ' +
country.isoCode +
" didn't have a pattern" +
( country.patternRegion ? ' so we use ' + country.patternRegion : '.' )
);
} );
return data;
}
|
javascript
|
{
"resource": ""
}
|
q58274
|
insertCountryAliases
|
validation
|
function insertCountryAliases( data ) {
Object.keys( aliases ).forEach( source => {
data[ source ] = data[ aliases[ source ] ];
} );
return data;
}
|
javascript
|
{
"resource": ""
}
|
q58275
|
WPCOMUndocumented
|
validation
|
function WPCOMUndocumented( token, reqHandler ) {
if ( ! ( this instanceof WPCOMUndocumented ) ) {
return new WPCOMUndocumented( token, reqHandler );
}
if ( 'function' === typeof token ) {
reqHandler = token;
token = null;
} else if ( token ) {
this.loadToken( token );
}
wpcomFactory.call( this, token, function( params, fn ) {
if ( this.isTokenLoaded() ) {
// authToken is used in wpcom-xhr-request,
// which is used for the signup flow in the REST Proxy
params = assign( {}, params, { authToken: this._token, token: this._token } );
}
return reqHandler( params, fn );
} );
debug( 'Extending wpcom with undocumented endpoints.' );
}
|
javascript
|
{
"resource": ""
}
|
q58276
|
AccountPasswordData
|
validation
|
function AccountPasswordData() {
this.validatedPassword = null;
this.charsets = {
lowerChars: 'abcdefghjkmnpqrstuvwxyz'.split( '' ),
upperChars: 'ABCDEFGHJKMNPQRSTUVWXYZ'.split( '' ),
digitChars: '23456789'.split( '' ),
specialChars: '!@#$%^&*'.split( '' ),
};
this.letterCharsets = pick( this.charsets, [ 'lowerChars', 'upperChars' ] );
}
|
javascript
|
{
"resource": ""
}
|
q58277
|
transferStatus
|
validation
|
function transferStatus( siteId, transferId, status, message, themeId ) {
return {
type: THEME_TRANSFER_STATUS_RECEIVE,
siteId,
transferId,
status,
message,
themeId,
};
}
|
javascript
|
{
"resource": ""
}
|
q58278
|
transferInitiateFailure
|
validation
|
function transferInitiateFailure( siteId, error, plugin ) {
const context = !! plugin ? 'plugin' : 'theme';
return dispatch => {
const themeInitiateFailureAction = {
type: THEME_TRANSFER_INITIATE_FAILURE,
siteId,
error,
};
dispatch(
withAnalytics(
recordTracksEvent( 'calypso_automated_transfer_initiate_failure', { plugin, context } ),
themeInitiateFailureAction
)
);
};
}
|
javascript
|
{
"resource": ""
}
|
q58279
|
suffixThemeIdForInstall
|
validation
|
function suffixThemeIdForInstall( state, siteId, themeId ) {
// AT sites do not use the -wpcom suffix
if ( isSiteAutomatedTransfer( state, siteId ) ) {
return themeId;
}
if ( ! isDownloadableFromWpcom( state, themeId ) ) {
return themeId;
}
return themeId + '-wpcom';
}
|
javascript
|
{
"resource": ""
}
|
q58280
|
queryDocs
|
validation
|
function queryDocs( query ) {
return docsIndex.search( query ).map( result => {
const doc = documents[ result.ref ],
snippet = makeSnippet( doc, query );
return {
path: doc.path,
title: doc.title,
snippet: snippet,
};
} );
}
|
javascript
|
{
"resource": ""
}
|
q58281
|
listDocs
|
validation
|
function listDocs( filePaths ) {
return filePaths.map( path => {
const doc = find( documents, entry => entry.path === path );
if ( doc ) {
return {
path: path,
title: doc.title,
snippet: defaultSnippet( doc ),
};
}
return {
path: path,
title: 'Not found: ' + path,
snippet: '',
};
} );
}
|
javascript
|
{
"resource": ""
}
|
q58282
|
escapeRegexString
|
validation
|
function escapeRegexString( token ) {
// taken from: https://github.com/sindresorhus/escape-string-regexp/blob/master/index.js
const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
return token.update( str => str.replace( matchOperatorsRe, '\\$&' ) );
}
|
javascript
|
{
"resource": ""
}
|
q58283
|
validation
|
function( fetchOptions ) {
const namespace = getNamespace( fetchOptions );
debug( 'getPaginationData:', namespace );
return {
fetchInitialized: _usersFetchedByNamespace.hasOwnProperty( namespace ),
totalUsers: _totalUsersByNamespace[ namespace ] || 0,
fetchingUsers: _fetchingUsersByNamespace[ namespace ] || false,
usersCurrentOffset: _offsetByNamespace[ namespace ],
numUsersFetched: _usersFetchedByNamespace[ namespace ],
fetchNameSpace: namespace,
};
}
|
javascript
|
{
"resource": ""
}
|
|
q58284
|
validation
|
function( fetchOptions ) {
let namespace = getNamespace( fetchOptions ),
siteId = fetchOptions.siteId,
users = [];
debug( 'getUsers:', namespace );
if ( ! _usersBySite[ siteId ] ) {
_usersBySite[ siteId ] = {};
}
if ( ! _userIDsByNamespace[ namespace ] ) {
return users;
}
_userIDsByNamespace[ namespace ].forEach( userId => {
if ( _usersBySite[ siteId ][ userId ] ) {
users.push( _usersBySite[ siteId ][ userId ] );
}
} );
return users;
}
|
javascript
|
{
"resource": ""
}
|
|
q58285
|
validation
|
function( site ) {
if ( ! site ) {
return [];
}
if ( ! _pluginsBySite[ site.ID ] && ! _fetching[ site.ID ] ) {
PluginsActions.fetchSitePlugins( site );
_fetching[ site.ID ] = true;
}
if ( ! _pluginsBySite[ site.ID ] ) {
return _pluginsBySite[ site.ID ];
}
return values( _pluginsBySite[ site.ID ] );
}
|
javascript
|
{
"resource": ""
}
|
|
q58286
|
validation
|
function( sites, pluginSlug ) {
let plugin,
plugins = this.getPlugins( sites ),
pluginSites;
if ( ! plugins ) {
return;
}
plugin = find( plugins, _filters.isEqual.bind( this, pluginSlug ) );
if ( ! plugin ) {
return null;
}
pluginSites = plugin.sites
.filter( site => site.visible )
.map( site => {
// clone the site object before adding a new property. Don't modify the return value of getSite
const pluginSite = clone( getSite( reduxGetState(), site.ID ) );
pluginSite.plugin = site.plugin;
return pluginSite;
} );
return pluginSites.sort( function( first, second ) {
return first.title.toLowerCase() > second.title.toLowerCase() ? 1 : -1;
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q58287
|
validation
|
function( sites, pluginSlug ) {
const installedOnSites = this.getSites( sites, pluginSlug ) || [];
return sites.filter( function( site ) {
if ( ! site.visible ) {
return false;
}
if ( site.jetpack && site.isSecondaryNetworkSite ) {
return false;
}
return installedOnSites.every( function( installedOnSite ) {
return installedOnSite.slug !== site.slug;
} );
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q58288
|
urlSafeBase64DecodeString
|
validation
|
function urlSafeBase64DecodeString( str ) {
const decodeMap = {
'-': '+',
_: '/',
'.': '=',
};
return atob( str.replace( /[-_.]/g, ch => decodeMap[ ch ] ) );
}
|
javascript
|
{
"resource": ""
}
|
q58289
|
disableToolbarTouchEvents
|
validation
|
function disableToolbarTouchEvents() {
editor.$( '.mce-toolbar:not(.mce-menubar)', document.body ).each( ( i, toolbar ) => {
toolbar.addEventListener( 'touchstart', event => {
event.stopImmediatePropagation();
} );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58290
|
hideToolbarFadeOnFullScroll
|
validation
|
function hideToolbarFadeOnFullScroll() {
editor
.$( [
editor.$( '.mce-inline-toolbar-grp .mce-container-body', document.body ),
editor.$( '.mce-toolbar-grp', editor.theme.panel.getEl() ),
] )
.each( ( i, toolbar ) => {
toolbar.on(
'scroll',
throttle( ( { target } ) => {
let action;
if ( target.scrollLeft === target.scrollWidth - target.clientWidth ) {
action = 'add';
} else if ( tinymce.DOM.hasClass( target, 'is-scrolled-full' ) ) {
action = 'remove';
}
if ( action ) {
const elements = editor.$( target );
if ( ! elements.hasClass( 'mce-container-body' ) ) {
elements.add( tinymce.DOM.getParent( target, '.mce-container-body' ) );
}
elements[ action + 'Class' ]( 'is-scrolled-full' );
}
}, 200 )
);
} );
}
|
javascript
|
{
"resource": ""
}
|
q58291
|
toggleToolbarsScrollableOnResize
|
validation
|
function toggleToolbarsScrollableOnResize() {
function toggleToolbarsScrollableClass() {
editor.$( '.mce-toolbar-grp', editor.theme.panel.getEl() ).each( ( i, toolbar ) => {
const isScrollable = toolbar.scrollWidth > toolbar.clientWidth;
editor.$( toolbar ).toggleClass( 'is-scrollable', isScrollable );
} );
}
window.addEventListener( 'resize', throttle( toggleToolbarsScrollableClass, 200 ) );
toggleToolbarsScrollableClass();
// Since some toolbars are hidden by default and report inaccurate
// dimensions when forced to be shown, we instead bind to the event
// when it's expected that they'll be visible
editor.on( 'wptoolbar', event => {
// Since an event handler is expected to set the toolbar property,
// set a timeout to wait until the toolbar has been assigned
setTimeout( () => {
if ( ! event.toolbar || ! event.toolbar.visible() ) {
return;
}
// For inline toolbars, the scrollable panel is the first child
// of the toolbar, so we compare its width against the parent
const toolbar = event.toolbar.getEl();
const isScrollable = toolbar.firstChild.scrollWidth > toolbar.clientWidth;
editor.dom.toggleClass( toolbar, 'is-scrollable', isScrollable );
}, 0 );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58292
|
warn
|
validation
|
function warn() {
if ( ! I18N.throwErrors ) {
return;
}
if ( 'undefined' !== typeof window && window.console && window.console.warn ) {
window.console.warn.apply( window.console, arguments );
}
}
|
javascript
|
{
"resource": ""
}
|
q58293
|
getJedArgs
|
validation
|
function getJedArgs( jedMethod, props ) {
switch ( jedMethod ) {
case 'gettext':
return [ props.original ];
case 'ngettext':
return [ props.original, props.plural, props.count ];
case 'npgettext':
return [ props.context, props.original, props.plural, props.count ];
case 'pgettext':
return [ props.context, props.original ];
}
return [];
}
|
javascript
|
{
"resource": ""
}
|
q58294
|
getTranslationFromJed
|
validation
|
function getTranslationFromJed( jed, options ) {
let jedMethod = 'gettext';
if ( options.context ) {
jedMethod = 'p' + jedMethod;
}
if ( typeof options.original === 'string' && typeof options.plural === 'string' ) {
jedMethod = 'n' + jedMethod;
}
const jedArgs = getJedArgs( jedMethod, options );
return jed[ jedMethod ].apply( jed, jedArgs );
}
|
javascript
|
{
"resource": ""
}
|
q58295
|
connectAccountFetchComplete
|
validation
|
function connectAccountFetchComplete( state = {}, action ) {
return Object.assign( {}, state, {
connectedUserID: action.connectedUserID || '',
displayName: action.displayName || '',
email: action.email || '',
error: action.error || '',
firstName: action.firstName || '',
isActivated: action.isActivated || false,
isDeauthorizing: false,
isRequesting: false,
lastName: action.lastName || '',
logo: action.logo || '',
} );
}
|
javascript
|
{
"resource": ""
}
|
q58296
|
connectAccountDeauthorizeComplete
|
validation
|
function connectAccountDeauthorizeComplete( state = {}, action ) {
return Object.assign( {}, state, {
connectedUserID: '',
displayName: '',
email: '',
error: action.error || '',
firstName: '',
isActivated: false,
isDeauthorizing: false,
isRequesting: false,
lastName: '',
logo: '',
} );
}
|
javascript
|
{
"resource": ""
}
|
q58297
|
connectAccountOAuthInitComplete
|
validation
|
function connectAccountOAuthInitComplete( state = {}, action ) {
return Object.assign( {}, state, {
isOAuthInitializing: false,
error: action.error || '',
oauthUrl: action.oauthUrl || '',
} );
}
|
javascript
|
{
"resource": ""
}
|
q58298
|
applyPrecision
|
validation
|
function applyPrecision( cost, precision ) {
const exponent = Math.pow( 10, precision );
return Math.ceil( cost * exponent ) / exponent;
}
|
javascript
|
{
"resource": ""
}
|
q58299
|
canDomainAddGSuite
|
validation
|
function canDomainAddGSuite( domainName ) {
const GOOGLE_APPS_INVALID_SUFFIXES = [ '.in', '.wpcomstaging.com' ];
const GOOGLE_APPS_BANNED_PHRASES = [ 'google' ];
const includesBannedPhrase = some( GOOGLE_APPS_BANNED_PHRASES, bannedPhrase =>
includes( domainName, bannedPhrase )
);
const hasInvalidSuffix = some( GOOGLE_APPS_INVALID_SUFFIXES, invalidSuffix =>
endsWith( domainName, invalidSuffix )
);
return ! ( hasInvalidSuffix || includesBannedPhrase || isGSuiteRestricted() );
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.