_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q24900 | delegate | train | function delegate(selector, events, method) {
$(document.body).delegate(selector,
(events.split ? events : events.join('.'+NAMESPACE + ' ')) + '.'+NAMESPACE,
function() {
var api = QTIP.api[ $.attr(this, ATTR_ID) ];
api && !api.disabled && method.apply(api, arguments);
}
);
} | javascript | {
"resource": ""
} |
q24901 | hoverIntent | train | function hoverIntent(hoverEvent) {
// Only continue if tooltip isn't disabled
if(this.disabled || this.destroyed) { return FALSE; }
// Cache the event data
this.cache.event = hoverEvent && $.event.fix(hoverEvent);
this.cache.target = hoverEvent && $(hoverEvent.target);
// Start the event sequence
clearTimeout(this.timers.show);
this.timers.show = delay.call(this,
function() { this.render(typeof hoverEvent === 'object' || options.show.ready); },
options.prerender ? 0 : options.show.delay
);
} | javascript | {
"resource": ""
} |
q24902 | stealFocus | train | function stealFocus(event) {
if(!elem.is(':visible')) { return; }
var target = $(event.target),
tooltip = current.tooltip,
container = target.closest(SELECTOR),
targetOnTop;
// Determine if input container target is above this
targetOnTop = container.length < 1 ? FALSE :
parseInt(container[0].style.zIndex, 10) > parseInt(tooltip[0].style.zIndex, 10);
// If we're showing a modal, but focus has landed on an input below
// this modal, divert focus to the first visible input in this modal
// or if we can't find one... the tooltip itself
if(!targetOnTop && target.closest(SELECTOR)[0] !== tooltip[0]) {
focusInputs(target);
}
} | javascript | {
"resource": ""
} |
q24903 | calculate | train | function calculate(side, otherSide, type, adjustment, side1, side2, lengthName, targetLength, elemLength) {
var initialPos = position[side1],
mySide = my[side],
atSide = at[side],
isShift = type === SHIFT,
myLength = mySide === side1 ? elemLength : mySide === side2 ? -elemLength : -elemLength / 2,
atLength = atSide === side1 ? targetLength : atSide === side2 ? -targetLength : -targetLength / 2,
sideOffset = viewportScroll[side1] + viewportOffset[side1] - (containerStatic ? 0 : containerOffset[side1]),
overflow1 = sideOffset - initialPos,
overflow2 = initialPos + elemLength - (lengthName === WIDTH ? viewportWidth : viewportHeight) - sideOffset,
offset = myLength - (my.precedance === side || mySide === my[otherSide] ? atLength : 0) - (atSide === CENTER ? targetLength / 2 : 0);
// shift
if(isShift) {
offset = (mySide === side1 ? 1 : -1) * myLength;
// Adjust position but keep it within viewport dimensions
position[side1] += overflow1 > 0 ? overflow1 : overflow2 > 0 ? -overflow2 : 0;
position[side1] = Math.max(
-containerOffset[side1] + viewportOffset[side1],
initialPos - offset,
Math.min(
Math.max(
-containerOffset[side1] + viewportOffset[side1] + (lengthName === WIDTH ? viewportWidth : viewportHeight),
initialPos + offset
),
position[side1],
// Make sure we don't adjust complete off the element when using 'center'
mySide === 'center' ? initialPos - myLength : 1E9
)
);
}
// flip/flipinvert
else {
// Update adjustment amount depending on if using flipinvert or flip
adjustment *= type === FLIPINVERT ? 2 : 0;
// Check for overflow on the left/top
if(overflow1 > 0 && (mySide !== side1 || overflow2 > 0)) {
position[side1] -= offset + adjustment;
newMy.invert(side, side1);
}
// Check for overflow on the bottom/right
else if(overflow2 > 0 && (mySide !== side2 || overflow1 > 0) ) {
position[side1] -= (mySide === CENTER ? -offset : offset) + adjustment;
newMy.invert(side, side2);
}
// Make sure we haven't made things worse with the adjustment and reset if so
if(position[side1] < viewportScroll[side1] && -position[side1] > overflow2) {
position[side1] = initialPos; newMy = my.clone();
}
}
return position[side1] - initialPos;
} | javascript | {
"resource": ""
} |
q24904 | zeroBuffer | train | function zeroBuffer(buf) {
for (var i = 0; i < buf.length; i++) {
buf[i] = 0;
}
return buf;
} | javascript | {
"resource": ""
} |
q24905 | ErrorAbstract | train | function ErrorAbstract(msg, constructor) {
this.message = msg;
Error.call(this, this.message);
/* istanbul ignore else */
if (canCapture) {
Error.captureStackTrace(this, constructor);
} else if (canStack) {
this.stack = new Error().stack;
} else {
this.stack = '';
}
} | javascript | {
"resource": ""
} |
q24906 | formatResolutionText | train | function formatResolutionText(resolution, maxResolutionSize) {
const pp = precisionPrefix(maxResolutionSize, resolution);
const f = formatPrefix(`.${pp}`, resolution);
const formattedResolution = f(resolution);
return formattedResolution;
} | javascript | {
"resource": ""
} |
q24907 | getResolutionBasedResolutionText | train | function getResolutionBasedResolutionText(resolutions, zoomLevel) {
const sortedResolutions = resolutions.map(x => +x).sort((a, b) => b - a);
const resolution = sortedResolutions[zoomLevel];
const maxResolutionSize = sortedResolutions[sortedResolutions.length - 1];
return formatResolutionText(resolution, maxResolutionSize);
} | javascript | {
"resource": ""
} |
q24908 | getWidthBasedResolutionText | train | function getWidthBasedResolutionText(
zoomLevel, maxWidth, binsPerDimension, maxZoom
) {
const resolution = maxWidth / ((2 ** zoomLevel) * binsPerDimension);
// we can't display a NaN resolution
if (!Number.isNaN(resolution)) {
// what is the maximum possible resolution?
// this will determine how we format the lower resolutions
const maxResolutionSize = maxWidth / ((2 ** maxZoom) * binsPerDimension);
const pp = precisionPrefix(maxResolutionSize, resolution);
const f = formatPrefix(`.${pp}`, resolution);
const formattedResolution = f(resolution);
return formattedResolution;
}
console.warn(
'NaN resolution, screen is probably too small. Dimensions:',
this.dimensions,
);
return '';
} | javascript | {
"resource": ""
} |
q24909 | json | train | async function json(url, callback, pubSub) {
// Fritz: What is going on here? Can someone explain?
if (url.indexOf('hg19') >= 0) {
await sleep(1);
}
// console.log('url:', url);
return fetchEither(url, callback, 'json', pubSub);
} | javascript | {
"resource": ""
} |
q24910 | train | function (params) {
var url = params.url,
method = params.method,
helperParams = params.helperParams,
queryParams = params.queryParams,
bodyParams = params.bodyParams,
signatureParams,
message,
accessor = {},
allParams,
signature;
signatureParams = [
{system: true, key: OAUTH1_PARAMS.oauthConsumerKey, value: helperParams.consumerKey},
{system: true, key: OAUTH1_PARAMS.oauthToken, value: helperParams.token},
{system: true, key: OAUTH1_PARAMS.oauthSignatureMethod, value: helperParams.signatureMethod},
{system: true, key: OAUTH1_PARAMS.oauthTimestamp, value: helperParams.timestamp},
{system: true, key: OAUTH1_PARAMS.oauthNonce, value: helperParams.nonce},
{system: true, key: OAUTH1_PARAMS.oauthVersion, value: helperParams.version}
];
signatureParams = _.filter(signatureParams, function (param) {
return helperParams.addEmptyParamsToSign || param.value;
});
allParams = [].concat(signatureParams, queryParams, bodyParams);
message = {
action: url,
method: method,
parameters: _.map(allParams, function (param) {
return [param.key, param.value];
})
};
if (helperParams.consumerSecret) {
accessor.consumerSecret = helperParams.consumerSecret;
}
if (helperParams.tokenSecret) {
accessor.tokenSecret = helperParams.tokenSecret;
}
signature = oAuth1.SignatureMethod.sign(message, accessor);
signatureParams.push({system: true, key: OAUTH1_PARAMS.oauthSignature, value: signature});
return signatureParams;
} | javascript | {
"resource": ""
} | |
q24911 | train | function (headers, headerKey, defaultValue) {
var headerName = _.findKey(headers, function (value, key) {
return key.toLowerCase() === headerKey.toLowerCase();
});
if (!headerName) {
headers[headerKey] = defaultValue;
}
} | javascript | {
"resource": ""
} | |
q24912 | train | function (request, protocolProfileBehavior) {
if (!(request && request.body)) {
return;
}
var requestBody = request.body,
requestBodyType = requestBody.mode,
requestMethod = (typeof request.method === 'string') ? request.method.toLowerCase() : undefined,
bodyIsEmpty = requestBody.isEmpty(),
bodyIsDisabled = requestBody.disabled,
bodyContent = requestBody[requestBodyType],
// flag to decide body pruning for METHODS_WITHOUT_BODY
// @note this will be `true` even if protocolProfileBehavior is undefined
pruneBody = protocolProfileBehavior ? !protocolProfileBehavior.disableBodyPruning : true;
// early bailout for empty or disabled body (this area has some legacy shenanigans)
if (bodyIsEmpty || bodyIsDisabled) {
return;
}
// bail out if request method doesn't support body and pruneBody is true.
if (METHODS_WITHOUT_BODY[requestMethod] && pruneBody) {
return;
}
// even if body is not empty, but the body type is not known, we do not know how to parse the same
//
// @note if you'd like to support additional body types beyond formdata, url-encoding, etc, add the same to
// the builder module
if (!requestBodyBuilders.hasOwnProperty(requestBodyType)) {
return;
}
return requestBodyBuilders[requestBodyType](bodyContent, request);
} | javascript | {
"resource": ""
} | |
q24913 | train | function (buffer) {
var str = '',
uArrayVal = new Uint8Array(buffer),
i,
ii;
for (i = 0, ii = uArrayVal.length; i < ii; i++) {
str += String.fromCharCode(uArrayVal[i]);
}
return str;
} | javascript | {
"resource": ""
} | |
q24914 | train | function (arr) {
if (!_.isArray(arr)) {
return;
}
var obj = {},
key,
val,
i,
ii;
for (i = 0, ii = arr.length; i < ii; i += 2) {
key = arr[i];
val = arr[i + 1];
if (_.has(obj, key)) {
!_.isArray(obj[key]) && (obj[key] = [obj[key]]);
obj[key].push(val);
}
else {
obj[key] = val;
}
}
return obj;
} | javascript | {
"resource": ""
} | |
q24915 | train | function (Handler, name) {
if (!_.isFunction(Handler.init)) {
throw new Error('The handler for "' + name + '" does not have an "init" function, which is necessary');
}
if (!_.isFunction(Handler.pre)) {
throw new Error('The handler for "' + name + '" does not have a "pre" function, which is necessary');
}
if (!_.isFunction(Handler.post)) {
throw new Error('The handler for "' + name + '" does not have a "post" function, which is necessary');
}
if (!_.isFunction(Handler.sign)) {
throw new Error('The handler for "' + name + '" does not have a "sign" function, which is necessary');
}
Object.defineProperty(Handler, AUTH_TYPE_PROP, {
value: name,
configurable: false,
enumerable: false,
writable: false
});
AuthLoader.handlers[name] = Handler;
} | javascript | {
"resource": ""
} | |
q24916 | train | function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
var auth = context.auth,
originalAuth = context.originalItem.getAuth(),
originalAuthParams = originalAuth && originalAuth.parameters(),
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// bail out if there is no matching auth handler for the type
if (!authHandler) {
run.triggers.console(context.coords, 'warn', 'runtime: could not find a handler for auth: ' + auth.type);
return done();
}
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync all auth system parameters to the original auth
originalAuthParams && auth.parameters().each(function (param) {
param && param.system && originalAuthParams.upsert({key: param.key, value: param.value, system: true});
});
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
// warn the user but don't bubble it up
if (err) {
run.triggers.console(
context.coords,
'warn',
'runtime~' + auth.type + '.auth: there was an error validating auth: ' + (err.message || err),
err
);
return done();
}
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true, helper: auth.type + DOT_AUTH});
});
} | javascript | {
"resource": ""
} | |
q24917 | train | function (auth, done) {
!auth.get('nonce') && auth.set('nonce', randomString(6));
!_.parseInt(auth.get('timestamp')) && auth.set('timestamp', Math.floor(Date.now() / 1e3));
done(null, true);
} | javascript | {
"resource": ""
} | |
q24918 | train | function (params) {
return Hawk.header(url.parse(params.url), params.method, params);
} | javascript | {
"resource": ""
} | |
q24919 | train | function (context, item, desiredPayload, success, failure) {
// max retries exceeded
if (this.count >= MAX_REPLAY_COUNT) {
return failure(new Error('runtime: maximum intermediate request limit exceeded'));
}
// update replay count state
this.count++;
// update replay state to context
context.replayState = this.getReplayState();
// construct payload for request
var payload = _.defaults({
item: item,
// abortOnError makes sure request command bubbles errors
// so we can pass it on to the callback
abortOnError: true
}, desiredPayload);
// create item context from the new item
payload.context = createItemContext(payload, context);
this.run.immediate('httprequest', payload)
.done(function (response) {
success(null, response);
})
.catch(success);
} | javascript | {
"resource": ""
} | |
q24920 | train | function () {
try {
authHandler.sign(authInterface, context.item.request, function (err) {
// handle all types of errors in one place, see catch block
if (err) { throw err; }
done();
});
}
catch (err) {
// handles synchronous and asynchronous errors in auth.sign
run.triggers.console(context.coords,
'warn',
'runtime~' + authType + '.auth: could not sign the request: ' + (err.message || err),
err
);
// swallow the error, we've warned the user
done();
}
} | javascript | {
"resource": ""
} | |
q24921 | train | function (cb) {
if (_.isFunction(_.get(proxies, 'resolve'))) {
return cb(null, proxies.resolve(url));
}
return cb(null, undefined);
} | javascript | {
"resource": ""
} | |
q24922 | train | function (config, cb) {
if (config) {
return cb(null, config);
}
return _.isFunction(run.options.systemProxy) ? run.options.systemProxy(url, cb) : cb(null, undefined);
} | javascript | {
"resource": ""
} | |
q24923 | train | function (context, run, done) {
var request,
pfxPath,
keyPath,
certPath,
fileResolver,
certificate;
// A. Check if we have the file resolver
fileResolver = run.options.fileResolver;
if (!fileResolver) { return done(); } // No point going ahead
// B. Ensure we have the request
request = _.get(context.item, 'request');
if (!request) { return done(new Error('No request to resolve certificates for.')); }
// C. See if any cert should be sent, by performing a URL matching
certificate = run.options.certificates && run.options.certificates.resolveOne(request.url);
if (!certificate) { return done(); }
// D. Fetch the paths
// @todo: check why aren't we reading ca file (why are we not supporting ca file)
pfxPath = _.get(certificate, 'pfx.src');
keyPath = _.get(certificate, 'key.src');
certPath = _.get(certificate, 'cert.src');
// E. Read from the path, and add the values to the certificate, also associate
// the certificate with the current request.
async.mapValues({
pfx: pfxPath,
key: keyPath,
cert: certPath
}, function (value, key, next) {
// bail out if value is not defined
// @todo add test with server which only accepts cert file
if (!value) { return next(); }
// eslint-disable-next-line security/detect-non-literal-fs-filename
fileResolver.readFile(value, function (err, data) {
// Swallow the error after triggering a warning message for the user.
err && run.triggers.console(context.coords, 'warn',
`certificate "${key}" load error: ${(err.message || err)}`);
next(null, data);
});
}, function (err, fileContents) {
if (err) {
// Swallow the error after triggering a warning message for the user.
run.triggers.console(context.coords, 'warn', 'certificate load error: ' + (err.message || err));
return done();
}
if (fileContents) {
!_.isNil(fileContents.pfx) && _.set(certificate, 'pfx.value', fileContents.pfx);
!_.isNil(fileContents.key) && _.set(certificate, 'key.value', fileContents.key);
!_.isNil(fileContents.cert) && _.set(certificate, 'cert.value', fileContents.cert);
(fileContents.cert || fileContents.key || fileContents.pfx) && (request.certificate = certificate);
}
done();
});
} | javascript | {
"resource": ""
} | |
q24924 | train | function (cb, expect) {
if (_.isFunction(cb) && cb.__normalised) {
return meetExpectations(cb, expect);
}
var userback, // this var will be populated and returned
// keep a reference of all initial callbacks sent by user
callback = (_.isFunction(cb) && cb) || (_.isFunction(cb && cb.done) && cb.done),
callbackError = _.isFunction(cb && cb.error) && cb.error,
callbackSuccess = _.isFunction(cb && cb.success) && cb.success;
// create master callback that calls these user provided callbacks
userback = _.assign(function (err) {
// if common callback is defined, call that
callback && callback.apply(this, arguments);
// for special error and success, call them if they are user defined
if (err) {
callbackError && callbackError.apply(this, arguments);
}
else {
// remove the extra error param before calling success
callbackSuccess && callbackSuccess.apply(this, (Array.prototype.shift.call(arguments), arguments));
}
}, _.isPlainObject(cb) && cb, { // override error, success and done
error: function () {
return userback.apply(this, arguments);
},
success: function () {
// inject null to arguments and call the main callback
userback.apply(this, (Array.prototype.unshift.call(arguments, null), arguments));
},
done: function () {
return userback.apply(this, arguments);
},
__normalised: true
});
return meetExpectations(userback, expect);
} | javascript | {
"resource": ""
} | |
q24925 | train | function (flags, callback, args, ms) {
var status = {},
sealed;
// ensure that the callback times out after a while
callback = backpack.timeback(callback, ms, null, function () {
sealed = true;
});
return function (err, flag, value) {
if (sealed) { return; } // do not proceed of it is sealed
status[flag] = value;
if (err) { // on error we directly call the callback and seal subsequent calls
sealed = true;
status = null;
callback.call(status, err);
return;
}
// if any flag is not defined, we exit. when all flags hold a value, we know that the end callback has to be
// executed.
for (var i = 0, ii = flags.length; i < ii; i++) {
if (!status.hasOwnProperty(flags[i])) { return; }
}
sealed = true;
status = null;
callback.apply(status, args);
};
} | javascript | {
"resource": ""
} | |
q24926 | train | function (callback, ms, scope, when) {
ms = Number(ms);
// if np callback time is specified, just return the callback function and exit. this is because we do need to
// track timeout in 0ms
if (!ms) {
return callback;
}
var sealed = false,
irq = setTimeout(function () { // irq = interrupt request
sealed = true;
irq = null;
when && when.call(scope || this);
callback.call(scope || this, new Error('callback timed out'));
}, ms);
return function () {
// if sealed, it means that timeout has elapsed and we accept no future callback
if (sealed) { return undefined; }
// otherwise we clear timeout and allow the callback to be executed. note that we do not seal the function
// since we should allow multiple callback calls.
irq && (irq = clearTimeout(irq));
return callback.apply(scope || this, arguments);
};
} | javascript | {
"resource": ""
} | |
q24927 | train | function (options) {
// combine runner config and make a copy
var runOptions = _.merge(_.omit(options, ['environment', 'globals', 'data']), this.options.run) || {};
// start timeout sanitization
!runOptions.timeout && (runOptions.timeout = {});
_.mergeWith(runOptions.timeout, defaultTimeouts, function (userTimeout, defaultTimeout) {
// non numbers, Infinity and missing values are set to default
if (!_.isFinite(userTimeout)) { return defaultTimeout; }
// 0 and negative numbers are set to Infinity, which only leaves positive numbers
return userTimeout > 0 ? userTimeout : Infinity;
});
return runOptions;
} | javascript | {
"resource": ""
} | |
q24928 | train | function (collection, options, callback) {
var self = this,
runOptions = this.prepareRunConfig(options);
callback = backpack.normalise(callback);
!_.isObject(options) && (options = {});
// @todo make the extract runnables interface better defined and documented
// - give the ownership of error to each strategy lookup functions
// - think about moving these codes into an extension command prior to waterfall
// - the third argument in callback that returns control, is ambiguous and can be removed if error is controlled
// by each lookup function.
// - the interface can be further broken down to have the "flattenNode" action be made common and not be
// required to be coded in each lookup strategy
//
// serialise the items into a linear array based on the lookup strategy provided as input
extractRunnableItems(collection, options.entrypoint, function (err, runnableItems, entrypoint) {
if (err || !runnableItems) { return callback(new Error('Error fetching run items')); }
// Bail out only if: abortOnError is set and the returned entrypoint is invalid
if (options.abortOnError && !entrypoint) {
// eslint-disable-next-line max-len
return callback(new Error(`Unable to find a folder or request: ${_.get(options, 'entrypoint.execute')}`));
}
return callback(null, (new Run({
items: runnableItems,
data: Runner.normaliseIterationData(options.data, options.iterationCount),
environment: options.environment,
globals: _.has(options, 'globals') ? options.globals : self.options.globals,
// @todo Move to item level to support Item and ItemGroup variables
collectionVariables: collection.variables,
certificates: options.certificates,
proxies: options.proxies
}, runOptions)));
});
} | javascript | {
"resource": ""
} | |
q24929 | train | function (callback) {
callback = backpack.ensure(callback, this);
if (this.paused) { return callback && callback(new Error('run: already paused')); }
// schedule the pause command as an interrupt and flag that the run is pausing
this.paused = true;
this.interrupt('pause', null, callback);
} | javascript | {
"resource": ""
} | |
q24930 | train | function (callback) {
callback = backpack.ensure(callback, this);
if (!this.paused) { return callback && callback(new Error('run: not paused')); }
// set flag that it is no longer paused and fire the stored callback for the command when it was paused
this.paused = false;
setTimeout(function () {
this.__resume();
delete this.__resume;
this.triggers.resume(null, this.state.cursor.current());
}.bind(this), 0);
callback && callback();
} | javascript | {
"resource": ""
} | |
q24931 | train | function (summarise, callback) {
if (_.isFunction(summarise) && !callback) {
callback = summarise;
summarise = true;
}
this.interrupt('abort', {
summarise: summarise
}, callback);
_.isFunction(this.__resume) && this.resume();
} | javascript | {
"resource": ""
} | |
q24932 | train | function (callback, scope) {
var coords = _.isFunction(callback) && this.current();
this.position = 0;
this.iteration = 0;
// send before and after values to the callback
return coords && callback.call(scope || this, null, this.current(), coords);
} | javascript | {
"resource": ""
} | |
q24933 | train | function (position, iteration, callback, scope) {
var coords = _.isFunction(callback) && this.current();
// if null or undefined implies use existing seek position
_.isNil(position) && (position = this.position);
_.isNil(iteration) && (iteration = this.iteration);
// make the pointers stay within boundary
if ((position >= this.length) || (iteration >= this.cycles) || (position < 0) || (iteration < 0) ||
isNaN(position) || isNaN(iteration)) {
return coords &&
callback.call(scope || this, new Error('runcursor: seeking out of bounds: ' + [position, iteration]));
}
// floor the numbers
position = ~~position;
iteration = ~~iteration;
// set the new positions
this.position = Cursor.validate(position, 0, this.length);
this.iteration = Cursor.validate(iteration, 0, this.cycles);
// finally execute the callback with the seek position
return coords && callback.call(scope || this, null, this.hasChanged(coords), this.current(), coords);
} | javascript | {
"resource": ""
} | |
q24934 | train | function (callback, scope) {
var position = this.position,
iteration = this.iteration,
coords;
// increment position
position += 1;
// check if we need to increment cycle
if (position >= this.length) {
// set position to 0 and increment iteration
position = 0;
iteration += 1;
if (iteration >= this.cycles) {
coords = _.isFunction(callback) && this.current();
coords.eof = true;
return coords && callback.call(scope || this, null, false, coords, coords);
}
coords && (coords.cr = true);
}
// finally handover the new coordinates to seek function
return this.seek(position, iteration, callback, scope);
} | javascript | {
"resource": ""
} | |
q24935 | train | function (coords) {
return _.isObject(coords) && !((this.position === coords.position) && (this.iteration === coords.iteration));
} | javascript | {
"resource": ""
} | |
q24936 | train | function () {
return {
position: this.position,
iteration: this.iteration,
length: this.length,
cycles: this.cycles,
empty: this.empty(),
eof: this.eof(),
bof: this.bof(),
cr: this.cr(),
ref: this.ref
};
} | javascript | {
"resource": ""
} | |
q24937 | train | function (name, payload, args) {
var processor = processors[name];
if (!_.isString(name) || !_.isFunction(processor)) {
throw new Error('run-instruction: invalid construction');
}
// ensure that payload is an object so that data storage can be done. also ensure arguments is an array
!_.isObject(payload) && (payload = {});
!_.isArray(args) && (args = []);
_.assign(this, /** @lends Instruction.prototype */ {
/**
* @type {String}
*/
action: name,
/**
* @type {Object}
*/
payload: payload,
/**
* @type {Array}
*/
in: args,
/**
* @type {Timings}
*/
timings: Timings.create(),
/**
* @private
* @type {Function}
*/
_processor: processor
});
// record the timing when this instruction was created
this.timings.record('created');
} | javascript | {
"resource": ""
} | |
q24938 | is_crossDomain | train | function is_crossDomain(url) {
var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/
// jQuery #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
var ajaxLocation
try { ajaxLocation = location.href }
catch (e) {
// Use the href attribute of an A element since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []
, parts = rurl.exec(url.toLowerCase() )
var result = !!(
parts &&
( parts[1] != ajaxLocParts[1]
|| parts[2] != ajaxLocParts[2]
|| (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))
)
)
//console.debug('is_crossDomain('+url+') -> ' + result)
return result
} | javascript | {
"resource": ""
} |
q24939 | _getDigestAuthHeader | train | function _getDigestAuthHeader (headers) {
return headers.find(function (property) {
return (property.key.toLowerCase() === WWW_AUTHENTICATE) && (_.startsWith(property.value, DIGEST_PREFIX));
});
} | javascript | {
"resource": ""
} |
q24940 | train | function (auth, response, done) {
if (auth.get(DISABLE_RETRY_REQUEST) || !response) {
return done(null, true);
}
var code,
realm,
nonce,
qop,
opaque,
authHeader,
authParams = {};
code = response.code;
authHeader = _getDigestAuthHeader(response.headers);
// If code is forbidden or unauthorized, and an auth header exists,
// we can extract the realm & the nonce, and replay the request.
// todo: add response.is4XX, response.is5XX, etc in the SDK.
if ((code === 401 || code === 403) && authHeader) {
nonce = _extractField(authHeader.value, nonceRegex);
realm = _extractField(authHeader.value, realmRegex);
qop = _extractField(authHeader.value, qopRegex);
opaque = _extractField(authHeader.value, opaqueRegex);
authParams.nonce = nonce;
authParams.realm = realm;
opaque && (authParams.opaque = opaque);
qop && (authParams.qop = qop);
if (authParams.qop || auth.get(QOP)) {
authParams.clientNonce = randomString(8);
authParams.nonceCount = ONE;
}
// if all the auth parameters sent by server were already present in auth definition then we do not retry
if (_.every(authParams, function (value, key) { return auth.get(key); })) {
return done(null, true);
}
auth.set(authParams);
return done(null, false);
}
done(null, true);
} | javascript | {
"resource": ""
} | |
q24941 | train | function (params) {
var algorithm = params.algorithm,
username = params.username,
realm = params.realm,
password = params.password,
method = params.method,
nonce = params.nonce,
nonceCount = params.nonceCount,
clientNonce = params.clientNonce,
opaque = params.opaque,
qop = params.qop,
uri = params.uri,
// RFC defined terms, http://tools.ietf.org/html/rfc2617#section-3
A0,
A1,
A2,
hashA1,
hashA2,
reqDigest,
headerParams;
if (algorithm === MD5_SESS) {
A0 = crypto.MD5(username + COLON + realm + COLON + password).toString();
A1 = A0 + COLON + nonce + COLON + clientNonce;
}
else {
A1 = username + COLON + realm + COLON + password;
}
if (qop === AUTH_INT) {
A2 = method + COLON + uri + COLON + crypto.MD5(params.body);
}
else {
A2 = method + COLON + uri;
}
hashA1 = crypto.MD5(A1).toString();
hashA2 = crypto.MD5(A2).toString();
if (qop === AUTH || qop === AUTH_INT) {
reqDigest = crypto.MD5([hashA1, nonce, nonceCount, clientNonce, qop, hashA2].join(COLON)).toString();
}
else {
reqDigest = crypto.MD5([hashA1, nonce, hashA2].join(COLON)).toString();
}
headerParams = [USERNAME_EQUALS_QUOTE + username + QUOTE,
REALM_EQUALS_QUOTE + realm + QUOTE,
NONCE_EQUALS_QUOTE + nonce + QUOTE,
URI_EQUALS_QUOTE + uri + QUOTE
];
algorithm && headerParams.push(ALGORITHM_EQUALS_QUOTE + algorithm + QUOTE);
if (qop === AUTH || qop === AUTH_INT) {
headerParams.push(QOP_EQUALS + qop);
}
if (qop === AUTH || qop === AUTH_INT || algorithm === MD5_SESS) {
nonceCount && headerParams.push(NC_EQUALS + nonceCount);
headerParams.push(CNONCE_EQUALS_QUOTE + clientNonce + QUOTE);
}
headerParams.push(RESPONSE_EQUALS_QUOTE + reqDigest + QUOTE);
opaque && headerParams.push(OPAQUE_EQUALS_QUOTE + opaque + QUOTE);
return DIGEST_PREFIX + headerParams.join(', ');
} | javascript | {
"resource": ""
} | |
q24942 | train | function (fn, ctx) {
// extract the arguments that are to be forwarded to the function to be called
var args = Array.prototype.slice.call(arguments, 2);
try {
(typeof fn === FUNCTION) && fn.apply(ctx || global, args);
}
catch (err) {
return err;
}
} | javascript | {
"resource": ""
} | |
q24943 | train | function (dest, src) {
var prop;
// update or add values from src
for (prop in src) {
if (src.hasOwnProperty(prop)) {
dest[prop] = src[prop];
}
}
// remove values that no longer exist
for (prop in dest) {
if (dest.hasOwnProperty(prop) && !src.hasOwnProperty(prop)) {
delete dest[prop];
}
}
return dest;
} | javascript | {
"resource": ""
} | |
q24944 | train | function (resolver, fileSrc, callback) {
// bail out if resolver not found.
if (!resolver) {
return callback(new Error('file resolver not supported'));
}
// bail out if resolver is not supported.
if (typeof resolver.stat !== FUNCTION || typeof resolver.createReadStream !== FUNCTION) {
return callback(new Error('file resolver interface mismatch'));
}
// bail out if file source is invalid or empty string.
if (!fileSrc || typeof fileSrc !== STRING) {
return callback(new Error('invalid or missing file source'));
}
// now that things are sanitized and validated, we transfer it to the
// stream reading utility function that does the heavy lifting of
// calling there resolver to return the stream
return createReadStream(resolver, fileSrc, callback);
} | javascript | {
"resource": ""
} | |
q24945 | escapeForIOSAndAndroid | train | function escapeForIOSAndAndroid(args) {
if (Platform.OS === 'android' || Platform.OS === 'ios') {
return map(args, escapeBlob)
} else {
return args
}
} | javascript | {
"resource": ""
} |
q24946 | SessionManagerFactory | train | function SessionManagerFactory(options) {
log.debug('[chimp][session-manager-factory] options are', options);
if (!options) {
throw new Error('options is required');
}
if (!options.port) {
throw new Error('options.port is required');
}
if (!options.browser && !options.deviceName) {
throw new Error('[chimp][session-manager-factory] options.browser or options.deviceName is required');
}
if (options.host && (options.host.indexOf('browserstack') > -1 || options.host.indexOf('saucelabs') > -1 || options.host.indexOf('testingbot') > -1)) {
if (!options.user || !options.key) {
throw new Error('[chimp][session-manager-factory] options.user and options.key are required');
}
if (options.host.indexOf('browserstack') > -1) {
return new BsManager(options);
} else if (options.host.indexOf('saucelabs') > -1) {
return new SlManager(options);
} else if (options.host.indexOf('testingbot') > -1) {
return new TbManager(options);
}
} else {
return new SessionManager(options);
}
} | javascript | {
"resource": ""
} |
q24947 | Jenkins | train | function Jenkins(opts) {
if (!(this instanceof Jenkins)) {
return new Jenkins(opts);
}
if (typeof opts === 'string') {
opts = { baseUrl: opts };
} else {
opts = opts || {};
}
opts = Object.assign({}, opts);
if (!opts.baseUrl) {
if (opts.url) {
opts.baseUrl = opts.url;
delete opts.url;
} else {
throw new Error('baseUrl required');
}
}
if (!opts.headers) {
opts.headers = {};
}
if (!opts.headers.referer) {
opts.headers.referer = opts.baseUrl + '/';
}
if (opts.request) {
throw new Error('request not longer supported');
}
opts.name = 'jenkins';
if (typeof opts.crumbIssuer === 'function') {
this._crumbIssuer = opts.crumbIssuer;
delete opts.crumbIssuer;
} else if (opts.crumbIssuer === true) {
this._crumbIssuer = utils.crumbIssuer;
}
if (opts.formData) {
if (typeof opts.formData !== 'function' || opts.formData.name !== 'FormData') {
throw new Error('formData is invalid');
}
this._formData = opts.formData;
delete opts.formData;
}
papi.Client.call(this, opts);
this._ext('onCreate', this._onCreate);
this._ext('onResponse', this._onResponse);
this.build = new Jenkins.Build(this);
this.crumbIssuer = new Jenkins.CrumbIssuer(this);
this.job = new Jenkins.Job(this);
this.label = new Jenkins.Label(this);
this.node = new Jenkins.Node(this);
this.queue = new Jenkins.Queue(this);
this.view = new Jenkins.View(this);
try {
if (opts.promisify) {
if (typeof opts.promisify === 'function') {
papi.tools.promisify(this, opts.promisify);
} else {
papi.tools.promisify(this);
}
}
} catch (err) {
err.message = 'promisify: ' + err.message;
throw err;
}
} | javascript | {
"resource": ""
} |
q24948 | ignoreErrorForStatusCodes | train | function ignoreErrorForStatusCodes() {
var statusCodes = Array.prototype.slice.call(arguments);
return function(ctx, next) {
if (ctx.err && ctx.res && statusCodes.indexOf(ctx.res.statusCode) !== -1) {
delete ctx.err;
}
next();
};
} | javascript | {
"resource": ""
} |
q24949 | require302 | train | function require302(message) {
return function(ctx, next) {
if (ctx.res && ctx.res.statusCode === 302) {
return next(false);
} else if (ctx.res) {
if (ctx.err) {
if (!ctx.res.headers['x-error']) ctx.err.message = message;
} else {
ctx.err = new Error(message);
}
return next(ctx.err);
}
next();
};
} | javascript | {
"resource": ""
} |
q24950 | parseName | train | function parseName(value) {
var jobParts = [];
var pathParts = (urlParse(value).pathname || '').split('/').filter(Boolean);
var state = 0;
var part;
// iterate until we find our first job, then collect the continuous job parts
// ['foo', 'job', 'a', 'job', 'b', 'bar', 'job', 'c'] => ['a', 'b']
loop:
for (var i = 0; i < pathParts.length; i++) {
part = pathParts[i];
switch (state) {
case 0:
if (part === 'job') state = 2;
break;
case 1:
if (part !== 'job') break loop;
state = 2;
break;
case 2:
jobParts.push(part);
state = 1;
break;
}
}
return jobParts.map(decodeURIComponent);
} | javascript | {
"resource": ""
} |
q24951 | FolderPath | train | function FolderPath(value) {
if (!(this instanceof FolderPath)) {
return new FolderPath(value);
}
if (Array.isArray(value)) {
this.value = value;
} else if (typeof value === 'string') {
if (value.match('^https?:\/\/')) {
this.value = parseName(value);
} else {
this.value = value.split('/').filter(Boolean);
}
} else {
this.value = [];
}
} | javascript | {
"resource": ""
} |
q24952 | crumbIssuer | train | function crumbIssuer(jenkins, callback) {
jenkins.crumbIssuer.get(function(err, data) {
if (err) return callback(err);
if (!data || !data.crumbRequestField || !data.crumb) {
return callback(new Error('Failed to get crumb'));
}
callback(null, {
headerName: data.crumbRequestField,
headerValue: data.crumb,
});
});
} | javascript | {
"resource": ""
} |
q24953 | isFileLike | train | function isFileLike(v) {
return Buffer.isBuffer(v) ||
typeof v === 'object' &&
typeof v.pipe === 'function' &&
v.readable !== false;
} | javascript | {
"resource": ""
} |
q24954 | LogStream | train | function LogStream(jenkins, opts) {
var self = this;
events.EventEmitter.call(self);
self._jenkins = jenkins;
opts = opts || {};
self._delay = opts.delay || 1000;
delete opts.delay;
self._opts = {};
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
self._opts[key] = opts[key];
}
}
self._opts.meta = true;
process.nextTick(function() { self._run(); });
} | javascript | {
"resource": ""
} |
q24955 | setRaspberryVersion | train | function setRaspberryVersion() {
if (currentPins) {
return Promise.resolve();
}
return new Promise(function(resolve, reject) {
fs.readFile('/proc/cpuinfo', 'utf8', function(err, data) {
if (err) {
return reject(err);
}
// Match the last 4 digits of the number following "Revision:"
var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
if (!match) {
var errorMessage = 'Unable to match Revision in /proc/cpuinfo: ' + data;
return reject(new Error(errorMessage));
}
var revisionNumber = parseInt(match[1], 16);
var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';
debug(
'seen hardware revision %d; using pin mode %s',
revisionNumber,
pinVersion
);
// Create a list of valid BCM pins for this Raspberry Pi version.
// This will be used to validate channel numbers in getPinBcm
currentValidBcmPins = []
Object.keys(PINS[pinVersion]).forEach(
function(pin) {
// Lookup the BCM pin for the RPI pin and add it to the list
currentValidBcmPins.push(PINS[pinVersion][pin]);
}
);
currentPins = PINS[pinVersion];
return resolve();
});
});
} | javascript | {
"resource": ""
} |
q24956 | listen | train | function listen(channel, onChange) {
var pin = getPinForCurrentMode(channel);
if (!exportedInputPins[pin] && !exportedOutputPins[pin]) {
throw new Error('Channel %d has not been exported', channel);
}
debug('listen for pin %d', pin);
var poller = new Epoll(function(err, innerfd, events) {
if (err) throw err
clearInterrupt(innerfd);
onChange(channel);
});
var fd = fs.openSync(PATH + '/gpio' + pin + '/value', 'r+');
clearInterrupt(fd);
poller.add(fd, Epoll.EPOLLPRI);
// Append ready-to-use remove function
pollers[pin] = function() {
poller.remove(fd).close();
}
} | javascript | {
"resource": ""
} |
q24957 | encode | train | function encode (n) {
var o = ''
var i = 0
var i1, i2, i3, e1, e2, e3, e4
n = utf8Encode(n)
while (i < n.length) {
i1 = n.charCodeAt(i++)
i2 = n.charCodeAt(i++)
i3 = n.charCodeAt(i++)
e1 = (i1 >> 2)
e2 = (((i1 & 3) << 4) | (i2 >> 4))
e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6))
e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63
o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4)
}
return o
} | javascript | {
"resource": ""
} |
q24958 | validateRecord | train | function validateRecord (table, record) {
invariant(
_.isString(table),
'Must provide a table'
)
invariant(
/^[a-z0-9_]{3,255}$/.test(table),
'Table must be between 3 and 255 characters and must ' +
'consist only of lower case letters, numbers, and _'
)
invariant(
_.isObject(record),
'Must provide a record'
)
} | javascript | {
"resource": ""
} |
q24959 | train | function (header) {
/**
* This property is the mimetype for the file
*
* @property mime
* @type {String}
*/
this.mime = null;
/**
* This is the file size in bytes
*
* @type {Number}
*/
this.size = null;
/**
* This is a Date object which represents the last time this file was modified
*
* @type {Date}
*/
this.lastModified = null;
/**
* This is the HTTP header as an Object for the file.
*
* @type {Object}
*/
this.httpHeader = null;
if (header) this.setFromHTTPHeader(header);
} | javascript | {
"resource": ""
} | |
q24960 | train | function (header) {
this.httpHeader = parseHTTPHeader(header);
if (this.httpHeader[ 'content-length' ]) this.size = this.httpHeader[ 'content-length' ];
if (this.httpHeader[ 'content-type' ]) this.mime = this.httpHeader[ 'content-type' ];
if (this.httpHeader[ 'last-modified' ]) this.lastModified = new Date(this.httpHeader[ 'last-modified' ]);
} | javascript | {
"resource": ""
} | |
q24961 | train | function (url) {
this.url = url;
if (this.canLoadUsingXHR()) {
this.xhr = new XMLHttpRequest();
this.xhr.open('GET', url, true);
this.xhr.onreadystatechange = this._onStateChange;
this.xhr.onprogress !== undefined && (this.xhr.onprogress = this._onProgress);
if (this.loadType !== LoaderBase.typeText) {
if (!checkIfGoodValue.call(this)) {
console.warn('Attempting to use incompatible load type ' + this.loadType + '. Switching it to ' + LoaderBase.typeText);
this.loadType = LoaderBase.typeText;
}
try {
this.loadTypeSet = checkResponseTypeSupport.call(this) && checkAndSetType(this.xhr, this.loadType);
} catch (e) {
this.loadTypeSet = false;
}
if (!this.loadTypeSet && (this.loadType === LoaderBase.typeBlob || this.loadType === LoaderBase.typeArraybuffer)) {
this.xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
}
this.xhr.send();
}
} | javascript | {
"resource": ""
} | |
q24962 | train | function (ev) {
var loaded = ev.loaded || ev.position;
var totalSize = ev.total || ev.totalSize;
if (totalSize) {
this._dispatchProgress(loaded / totalSize);
} else {
this._dispatchProgress(0);
}
} | javascript | {
"resource": ""
} | |
q24963 | train | function () {
if (this.xhr.readyState > 1) {
var status;
var waiting = false;
// Fix error in IE8 where status isn't available until readyState=4
try { status = this.xhr.status; } catch (e) { waiting = true; }
if (status === 200) {
switch (this.xhr.readyState) {
// send() has been called, and headers and status are available
case 2:
this.fileMeta = new FileMeta(this.xhr.getAllResponseHeaders());
this._dispatchStart();
break;
// Downloading; responseText holds partial data.
case 3:
// todo progress could be calculated here if onprogress does not exist on XHR
// this.onProgress.dispatch();
break;
// Done
case 4:
this._parseContent();
this._dispatchComplete();
break;
}
} else if (!waiting) {
this.xhr.onreadystatechange = undefined;
this._dispatchError(this.xhr.status);
}
}
} | javascript | {
"resource": ""
} | |
q24964 | train | function () {
if (this.loadTypeSet || this.loadType === LoaderBase.typeText) {
this.content = this.xhr.response || this.xhr.responseText;
} else {
switch (this.loadType) {
case LoaderBase.typeArraybuffer:
if (ArrayBuffer) {
this.content = stringToArrayBuffer(this.xhr.response);
} else {
throw new Error('This browser does not support ArrayBuffer');
}
break;
case LoaderBase.typeBlob:
case LoaderBase.typeVideo:
case LoaderBase.typeAudio:
if (Blob) {
if (!this.fileMeta) {
this.fileMeta = new FileMeta();
}
if (this.fileMeta.mime === null) {
this.fileMeta.mime = getMimeFromURL(this.url);
}
this.content = new Blob([ stringToArrayBuffer(this.xhr.response) ], { type: this.fileMeta.mime });
} else {
throw new Error('This browser does not support Blob');
}
break;
case LoaderBase.typeJSON:
this.content = JSON.parse(this.xhr.response);
break;
case LoaderBase.typeDocument:
// this needs some work pretty sure there's a better way to handle this
this.content = this.xhr.response;
break;
}
}
} | javascript | {
"resource": ""
} | |
q24965 | freezeAll | train | function freezeAll(exceptions) {
_freezeAllEvents = true;
if (!exceptions) {
return;
}
if (!utils.isArray(exceptions)) {
exceptions = [exceptions];
}
utils.forEach(exceptions, e => {
_freezeAllExceptions[e] = true;
});
} | javascript | {
"resource": ""
} |
q24966 | unfreezeAll | train | function unfreezeAll() {
_freezeAllEvents = false;
_freezeAllExceptions = {};
//unfreeze all instances
const keys = Object.keys(_frozenEventInstances);
for (let i = 0; i < keys.length; i++) {
const instance = _frozenEventInstances[keys[i]];
if (!instance) {
continue;
}
instance.unfreeze();
}
_frozenEventInstances = {};
} | javascript | {
"resource": ""
} |
q24967 | _mapOne | train | function _mapOne(name) {
const parts = name.split(".");
let current = _this.parent.model;
let current_name = "";
while (parts.length) {
current_name = parts.shift();
current = current[current_name];
}
return {
name,
model: current,
type: current ? current.getType() : null
};
} | javascript | {
"resource": ""
} |
q24968 | templateFunc | train | function templateFunc(str, data) {
const func = function(obj) {
return str.replace(/<%=([^%]*)%>/g, match => {
//match t("...")
let s = match.match(/t\s*\(([^)]+)\)/g);
//replace with translation
if (s.length) {
s = obj.t(s[0].match(/"([^"]+)"/g)[0].split('"').join(""));
}
//use object[name]
else {
s = match.match(/([a-z\-A-Z]+([a-z\-A-Z0-9]?[a-zA-Z0-9]?)?)/g)[0];
s = obj[s] || s;
}
return s;
});
};
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
const fn = !/<[a-z][\s\S]*>/i.test(str) ? templates[str] = templates[str] || templateFunc(globals.templates[str]) : func;
// Provide some basic currying to the user
return data ? fn(data) : fn;
} | javascript | {
"resource": ""
} |
q24969 | initSubmodel | train | function initSubmodel(attr, val, ctx, persistent) {
let submodel;
// if value is a value -> leaf
if (!utils.isPlainObject(val) || utils.isArray(val) || ctx.isObjectLeaf(attr)) {
const binds = {
//the submodel has changed (multiple times)
"change": onChange
};
submodel = new ModelLeaf(attr, val, ctx, binds, persistent);
}
// if value is an object -> model
else {
const binds = {
//the submodel has changed (multiple times)
"change": onChange,
//loading has started in this submodel (multiple times)
"hook_change": onHookChange,
// error triggered in loading
"load_error": (...args) => ctx.trigger(...args),
// interpolation completed
"dataLoaded": (...args) => ctx.trigger(...args),
//loading has ended in this submodel (multiple times)
"ready": onReady,
};
// if the value is an already instantiated submodel (Model or ModelLeaf)
// this is the case for example when a new componentmodel is made (in Component._modelMapping)
// it takes the submodels from the toolmodel and creates a new model for the component which refers
// to the instantiated submodels (by passing them as model values, and thus they reach here)
if (Model.isModel(val, true)) {
submodel = val;
submodel.on(binds);
}
// if it's just a plain object, create a new model
else {
// construct model
const modelType = attr.split("_")[0];
let Modl = Model.get(modelType, true);
if (!Modl) {
try {
Modl = require("../models/" + modelType).default;
} catch (err) {
Modl = Model;
}
}
submodel = new Modl(attr, val, ctx, binds);
// model is still frozen but will be unfrozen at end of original .set()
}
}
return submodel;
// Default event handlers for models
function onChange(evt, path) {
if (!ctx._ready) return; //block change propagation if model isnt ready
path = ctx._name + "." + path;
ctx.trigger(evt, path);
}
function onHookChange(evt, vals) {
ctx.trigger(evt, vals);
}
function onReady(evt, vals) {
//trigger only for submodel
ctx.setReady(false);
//wait to make sure it's not set false again in the next execution loop
utils.defer(() => {
ctx.setReady();
});
//ctx.trigger(evt, vals);
}
} | javascript | {
"resource": ""
} |
q24970 | onChange | train | function onChange(evt, path) {
if (!ctx._ready) return; //block change propagation if model isnt ready
path = ctx._name + "." + path;
ctx.trigger(evt, path);
} | javascript | {
"resource": ""
} |
q24971 | getIntervals | train | function getIntervals(ctx) {
return ctx._intervals || (ctx._parent ? getIntervals(ctx._parent) : new Intervals());
} | javascript | {
"resource": ""
} |
q24972 | train | function(val) {
if (val === undefined) {
return "undefined";
}
if (val === null) {
return "null";
}
let type = typeof val;
if (type === "object") {
type = getClass(val).toLowerCase();
}
if (type === "number") {
return val.toString().indexOf(".") > 0 ?
"float" :
"integer";
}
return type;
} | javascript | {
"resource": ""
} | |
q24973 | train | function(a, b) {
if (a !== b) {
const atype = whatis(a);
const btype = whatis(b);
if (atype === btype) {
return _equal.hasOwnProperty(atype) ? _equal[atype](a, b) : a == b;
}
return false;
}
return true;
} | javascript | {
"resource": ""
} | |
q24974 | deepCloneArray | train | function deepCloneArray(arr) {
const clone = [];
forEach(arr, (item, index) => {
if (typeof item === "object" && item !== null) {
if (isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
} | javascript | {
"resource": ""
} |
q24975 | finish | train | function finish(err) {
if (!calledDone) {
calledDone = true;
exports.finalize(err, resolve, reject);
}
} | javascript | {
"resource": ""
} |
q24976 | train | function() {
return window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW];
} | javascript | {
"resource": ""
} | |
q24977 | train | function() {
return window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH];
} | javascript | {
"resource": ""
} | |
q24978 | train | function(event) {
if(event.preventDefault && event.cancelable)
event.preventDefault();
else
event.returnValue = false;
} | javascript | {
"resource": ""
} | |
q24979 | train | function(event) {
event = event.originalEvent || event;
var strPage = 'page';
var strClient = 'client';
var strX = 'X';
var strY = 'Y';
var target = event.target || event.srcElement || document;
var eventDoc = target.ownerDocument || document;
var doc = eventDoc.documentElement;
var body = eventDoc.body;
//if touch event return return pageX/Y of it
if(event.touches !== undefined) {
var touch = event.touches[0];
return {
x : touch[strPage + strX],
y : touch[strPage + strY]
}
}
// Calculate pageX/Y if not native supported
if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) {
return {
x : event[strClient + strX] +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0),
y : event[strClient + strY] +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0)
}
}
return {
x : event[strPage + strX],
y : event[strPage + strY]
};
} | javascript | {
"resource": ""
} | |
q24980 | train | function(event) {
var button = event.button;
if (!event.which && button !== undefined)
return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
else
return event.which;
} | javascript | {
"resource": ""
} | |
q24981 | train | function(item, arr) {
for (var i = 0; i < arr[LEXICON.l]; i++)
//Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared
try {
if (arr[i] === item)
return i;
}
catch(e) { }
return -1;
} | javascript | {
"resource": ""
} | |
q24982 | train | function(arr) {
var def = Array.isArray;
return def ? def(arr) : this.type(arr) == TYPES.a;
} | javascript | {
"resource": ""
} | |
q24983 | initOverlayScrollbarsStatics | train | function initOverlayScrollbarsStatics() {
if(!_pluginsGlobals)
_pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults);
if(!_pluginsAutoUpdateLoop)
_pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals);
} | javascript | {
"resource": ""
} |
q24984 | train | function() {
if(_loopingInstances[_strLength] > 0 && _loopIsActive) {
_loopID = COMPATIBILITY.rAF()(function () {
loop();
});
var timeNew = COMPATIBILITY.now();
var timeDelta = timeNew - _loopTimeOld;
var lowestInterval;
var instance;
var instanceOptions;
var instanceAutoUpdateAllowed;
var instanceAutoUpdateInterval;
var now;
if (timeDelta > _loopInterval) {
_loopTimeOld = timeNew - (timeDelta % _loopInterval);
lowestInterval = _loopIntervalDefault;
for(var i = 0; i < _loopingInstances[_strLength]; i++) {
instance = _loopingInstances[i];
if (instance !== undefined) {
instanceOptions = instance.options();
instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate];
instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]);
now = COMPATIBILITY.now();
if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) {
instance.update('auto');
_loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval);
}
lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval));
}
}
_loopInterval = lowestInterval;
}
} else {
_loopInterval = _loopIntervalDefault;
}
} | javascript | {
"resource": ""
} | |
q24985 | removePassiveEventListener | train | function removePassiveEventListener(element, eventNames, listener) {
var events = eventNames.split(_strSpace);
for (var i = 0; i < events.length; i++)
element[0].removeEventListener(events[i], listener, {passive: true});
} | javascript | {
"resource": ""
} |
q24986 | train | function () {
/*
var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var expandChildCSS = {};
expandChildCSS[_strWidth] = sizeResetWidth;
expandChildCSS[_strHeight] = sizeResetHeight;
expandElementChild.css(expandChildCSS);
expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
*/
expandElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum);
shrinkElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum);
} | javascript | {
"resource": ""
} | |
q24987 | removeResizeObserver | train | function removeResizeObserver(targetElement) {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
element[_strResizeObserverProperty].disconnect();
delete element[_strResizeObserverProperty];
}
else {
remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0));
}
} | javascript | {
"resource": ""
} |
q24988 | connectMutationObservers | train | function connectMutationObservers() {
if (_supportMutationObserver && !_mutationObserversConnected) {
_mutationObserverHost.observe(_hostElementNative, {
attributes: true,
attributeOldValue: true,
attributeFilter: [LEXICON.i, LEXICON.c, LEXICON.s]
});
_mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, {
attributes: true,
attributeOldValue: true,
subtree: !_isTextarea,
childList: !_isTextarea,
characterData: !_isTextarea,
attributeFilter: _isTextarea ? ['wrap', 'cols', 'rows'] : [LEXICON.i, LEXICON.c, LEXICON.s]
});
_mutationObserversConnected = true;
}
} | javascript | {
"resource": ""
} |
q24989 | hostOnMouseMove | train | function hostOnMouseMove() {
if (_scrollbarsAutoHideMove) {
refreshScrollbarsAutoHide(true);
clearTimeout(_scrollbarsAutoHideMoveTimeoutId);
_scrollbarsAutoHideMoveTimeoutId = setTimeout(function () {
if (_scrollbarsAutoHideMove && !_destroyed)
refreshScrollbarsAutoHide(false);
}, 100);
}
} | javascript | {
"resource": ""
} |
q24990 | isUnknownMutation | train | function isUnknownMutation(mutation) {
var attributeName = mutation.attributeName;
var mutationTarget = mutation.target;
var mutationType = mutation.type;
var strClosest = 'closest';
if (mutationTarget === _contentElementNative)
return attributeName === null;
if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) {
//ignore className changes by the plugin
if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement))
return hostClassNamesChanged(mutation.oldValue, mutationTarget.getAttribute(LEXICON.c));
//only do it of browser support it natively
if (typeof mutationTarget[strClosest] != TYPES.f)
return true;
if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null)
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q24991 | updateAutoContentSizeChanged | train | function updateAutoContentSizeChanged() {
if (_isSleeping)
return false;
var float;
var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0;
var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea;
var viewportScrollSize = { };
var css = { };
var bodyMinSizeC;
var changed;
var viewportScrollSizeChanged;
//fix for https://bugzilla.mozilla.org/show_bug.cgi?id=1439305, it only works with "clipAlways : true"
//it can work with "clipAlways : false" too, but we had to set the overflow of the viewportElement to hidden every time before measuring
if(_restrictedMeasuring) {
viewportScrollSize = {
x : _viewportElementNative[LEXICON.sW],
y : _viewportElementNative[LEXICON.sH]
}
}
if (setCSS) {
float = _contentElement.css(_strFloat);
css[_strFloat] = _isRTL ? _strRight : _strLeft;
css[_strWidth] = _strAuto;
_contentElement.css(css);
}
var contentElementScrollSize = {
w: getContentMeasureElement()[LEXICON.sW] + textareaValueLength,
h: getContentMeasureElement()[LEXICON.sH] + textareaValueLength
};
if (setCSS) {
css[_strFloat] = float;
css[_strWidth] = _strHundredPercent;
_contentElement.css(css);
}
bodyMinSizeC = bodyMinSizeChanged();
changed = checkCacheDouble(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache);
viewportScrollSizeChanged = checkCacheDouble(viewportScrollSize, _viewportScrollSizeCache, _strX, _strY);
_contentElementScrollSizeChangeDetectedCache = contentElementScrollSize;
_viewportScrollSizeCache = viewportScrollSize;
return changed || bodyMinSizeC || viewportScrollSizeChanged;
} | javascript | {
"resource": ""
} |
q24992 | isSizeAffectingCSSProperty | train | function isSizeAffectingCSSProperty(propertyName) {
if (!_initialized)
return true;
var flexGrow = 'flex-grow';
var flexShrink = 'flex-shrink';
var flexBasis = 'flex-basis';
var affectingPropsX = [
_strWidth,
_strMinMinus + _strWidth,
_strMaxMinus + _strWidth,
_strMarginMinus + _strLeft,
_strMarginMinus + _strRight,
_strLeft,
_strRight,
'font-weight',
'word-spacing',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsXContentBox = [
_strPaddingMinus + _strLeft,
_strPaddingMinus + _strRight,
_strBorderMinus + _strLeft + _strWidth,
_strBorderMinus + _strRight + _strWidth
];
var affectingPropsY = [
_strHeight,
_strMinMinus + _strHeight,
_strMaxMinus + _strHeight,
_strMarginMinus + _strTop,
_strMarginMinus + _strBottom,
_strTop,
_strBottom,
'line-height',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsYContentBox = [
_strPaddingMinus + _strTop,
_strPaddingMinus + _strBottom,
_strBorderMinus + _strTop + _strWidth,
_strBorderMinus + _strBottom + _strWidth
];
var _strS = 's';
var _strVS = 'v-s';
var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS;
var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS;
var sizeIsAffected = false;
var checkPropertyName = function (arr, name) {
for (var i = 0; i < arr[LEXICON.l]; i++) {
if (arr[i] === name)
return true;
}
return false;
};
if (checkY) {
sizeIsAffected = checkPropertyName(affectingPropsY, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName);
}
if (checkX && !sizeIsAffected) {
sizeIsAffected = checkPropertyName(affectingPropsX, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName);
}
return sizeIsAffected;
} | javascript | {
"resource": ""
} |
q24993 | refreshScrollbarAppearance | train | function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) {
var scrollbarClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden;
var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement;
if (shallBeVisible)
removeClass(_hostElement, scrollbarClassName);
else
addClass(_hostElement, scrollbarClassName);
if (canScroll)
removeClass(scrollbarElement, _classNameScrollbarUnusable);
else
addClass(scrollbarElement, _classNameScrollbarUnusable);
} | javascript | {
"resource": ""
} |
q24994 | refreshScrollbarHandleLength | train | function refreshScrollbarHandleLength(isHorizontal) {
var handleCSS = {};
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var digit = 1000000;
//get and apply intended handle length
var handleRatio = MATH.min(1, (_hostSizeCache[scrollbarVars._w_h] - (_paddingAbsoluteCache ? (isHorizontal ? _paddingX : _paddingY) : 0)) / _contentScrollSizeCache[scrollbarVars._w_h]);
handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + "%"; //the last * digit / digit is for flooring to the 4th digit
if (!nativeOverlayScrollbarsAreActive())
scrollbarVars._handle.css(handleCSS);
//measure the handle length to respect min & max length
scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height];
scrollbarVarsInfo._handleLengthRatio = handleRatio;
} | javascript | {
"resource": ""
} |
q24995 | refreshScrollbarsInteractive | train | function refreshScrollbarsInteractive(isTrack, value) {
var action = value ? 'removeClass' : 'addClass';
var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement;
var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement;
var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff;
element1[action](className);
element2[action](className);
} | javascript | {
"resource": ""
} |
q24996 | getScrollbarVars | train | function getScrollbarVars(isHorizontal) {
return {
_width_height: isHorizontal ? _strWidth : _strHeight,
_Width_Height: isHorizontal ? 'Width' : 'Height',
_left_top: isHorizontal ? _strLeft : _strTop,
_Left_Top: isHorizontal ? 'Left' : 'Top',
_x_y: isHorizontal ? _strX : _strY,
_X_Y: isHorizontal ? 'X' : 'Y',
_w_h: isHorizontal ? 'w' : 'h',
_l_t: isHorizontal ? 'l' : 't',
_track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement,
_handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement,
_scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement,
_info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo
};
} | javascript | {
"resource": ""
} |
q24997 | setupScrollbarCornerEvents | train | function setupScrollbarCornerEvents() {
var insideIFrame = _windowElementNative.top !== _windowElementNative;
var mouseDownPosition = { };
var mouseDownSize = { };
var mouseDownInvertedScale = { };
_resizeOnMouseTouchDown = function(event) {
if (onMouseTouchDownContinue(event)) {
if (_mutationObserversConnected) {
_resizeReconnectMutationObserver = true;
disconnectMutationObservers();
}
mouseDownPosition = getCoordinates(event);
mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0);
mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0);
mouseDownInvertedScale = getHostElementInvertedScale();
_documentElement.on(_strSelectStartEvent, documentOnSelectStart)
.on(_strMouseTouchMoveEvent, documentDragMove)
.on(_strMouseTouchUpEvent, documentMouseTouchUp);
addClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.setCapture)
_scrollbarCornerElement.setCapture();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
};
function documentDragMove(event) {
if (onMouseTouchDownContinue(event)) {
var pageOffset = getCoordinates(event);
var hostElementCSS = { };
if (_resizeHorizontal || _resizeBoth)
hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x);
if (_resizeVertical || _resizeBoth)
hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y);
_hostElement.css(hostElementCSS);
COMPATIBILITY.stpP(event);
}
else {
documentMouseTouchUp(event);
}
}
function documentMouseTouchUp(event) {
var eventIsTrusted = event !== undefined;
_documentElement.off(_strSelectStartEvent, documentOnSelectStart)
.off(_strMouseTouchMoveEvent, documentDragMove)
.off(_strMouseTouchUpEvent, documentMouseTouchUp);
removeClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.releaseCapture)
_scrollbarCornerElement.releaseCapture();
if (eventIsTrusted) {
if (_resizeReconnectMutationObserver)
connectMutationObservers();
_base.update(_strAuto);
}
_resizeReconnectMutationObserver = false;
}
function onMouseTouchDownContinue(event) {
var originalEvent = event.originalEvent || event;
var isTouchEvent = originalEvent.touches !== undefined;
return _isSleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
}
function getCoordinates(event) {
return _msieVersion && insideIFrame ? { x : event.screenX , y : event.screenY } : COMPATIBILITY.page(event);
}
} | javascript | {
"resource": ""
} |
q24998 | setTopRightBottomLeft | train | function setTopRightBottomLeft(targetCSSObject, prefix, values) {
if (values === undefined)
values = [_strEmpty, _strEmpty, _strEmpty, _strEmpty];
targetCSSObject[prefix + _strTop] = values[0];
targetCSSObject[prefix + _strRight] = values[1];
targetCSSObject[prefix + _strBottom] = values[2];
targetCSSObject[prefix + _strLeft] = values[3];
} | javascript | {
"resource": ""
} |
q24999 | getCSSTransitionString | train | function getCSSTransitionString(element) {
var transitionStr = VENDORS._cssProperty('transition');
var assembledValue = element.css(transitionStr);
if(assembledValue)
return assembledValue;
var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*';
var regExpMain = new RegExp(regExpString);
var regExpValidate = new RegExp('^(' + regExpString + ')+$');
var properties = 'property duration timing-function delay'.split(' ');
var result = [ ];
var strResult;
var valueArray;
var i = 0;
var j;
var splitCssStyleByComma = function(str) {
strResult = [ ];
if (!str.match(regExpValidate))
return str;
while (str.match(regExpMain)) {
strResult.push(RegExp.$1);
str = str.replace(regExpMain, _strEmpty);
}
return strResult;
};
for (; i < properties[LEXICON.l]; i++) {
valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i]));
for (j = 0; j < valueArray[LEXICON.l]; j++)
result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j];
}
return result.join(', ');
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.