_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q20300 | fin | train | function fin(promise, finalPromiseFactory) {
return promise.then(function (res) {
return finalPromiseFactory().then(function () {
return res;
});
}, function (reason) {
return finalPromiseFactory().then(function () {
throw reason;
});
});
} | javascript | {
"resource": ""
} |
q20301 | sumsqr | train | function sumsqr(values) {
var _sumsqr = 0;
for (var i = 0, len = values.length; i < len; i++) {
var num = values[i];
_sumsqr += (num * num);
}
return _sumsqr;
} | javascript | {
"resource": ""
} |
q20302 | traverseRevTree | train | function traverseRevTree(revs, callback) {
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var branches = tree[2];
var newCtx =
callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
for (var i = 0, len = branche... | javascript | {
"resource": ""
} |
q20303 | collectConflicts | train | function collectConflicts(metadata) {
var win = winningRev(metadata);
var leaves = collectLeaves(metadata.rev_tree);
var conflicts = [];
for (var i = 0, len = leaves.length; i < len; i++) {
var leaf = leaves[i];
if (leaf.rev !== win && !leaf.opts.deleted) {
conflicts.push(leaf.rev);
}
}
re... | javascript | {
"resource": ""
} |
q20304 | compactTree | train | function compactTree(metadata) {
var revs = [];
traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
revHash, ctx, opts) {
if (opts.status === 'available' && !isLeaf) {
revs.push(pos + '-' + revHash);
opts.status = 'missing';
}
});
return r... | javascript | {
"resource": ""
} |
q20305 | rootToLeaf | train | function rootToLeaf(revs) {
var paths = [];
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var id = tree[0];
var opts = tree[1];
var branches = tree[2];
var isLeaf = branches.length === 0;
var history = node.history ? ... | javascript | {
"resource": ""
} |
q20306 | binarySearch | train | function binarySearch(arr, item, comparator) {
var low = 0;
var high = arr.length;
var mid;
while (low < high) {
mid = (low + high) >>> 1;
if (comparator(arr[mid], item) < 0) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
} | javascript | {
"resource": ""
} |
q20307 | insertSorted | train | function insertSorted(arr, item, comparator) {
var idx = binarySearch(arr, item, comparator);
arr.splice(idx, 0, item);
} | javascript | {
"resource": ""
} |
q20308 | pathToTree | train | function pathToTree(path, numStemmed) {
var root;
var leaf;
for (var i = numStemmed, len = path.length; i < len; i++) {
var node = path[i];
var currentLeaf = [node.id, node.opts, []];
if (leaf) {
leaf[2].push(currentLeaf);
leaf = currentLeaf;
} else {
root = leaf = currentLeaf;
... | javascript | {
"resource": ""
} |
q20309 | mergeTree | train | function mergeTree(in_tree1, in_tree2) {
var queue = [{tree1: in_tree1, tree2: in_tree2}];
var conflicts = false;
while (queue.length > 0) {
var item = queue.pop();
var tree1 = item.tree1;
var tree2 = item.tree2;
if (tree1[1].status || tree2[1].status) {
tree1[1].status =
(tree1[1].... | javascript | {
"resource": ""
} |
q20310 | stem | train | function stem(tree, depth) {
// First we break out the tree into a complete list of root to leaf paths
var paths = rootToLeaf(tree);
var stemmedRevs;
var result;
for (var i = 0, len = paths.length; i < len; i++) {
// Then for each path, we cut off the start of the path based on the
// `depth` to stem... | javascript | {
"resource": ""
} |
q20311 | revExists | train | function revExists(revs, rev) {
var toVisit = revs.slice();
var splitRev = rev.split('-');
var targetPos = parseInt(splitRev[0], 10);
var targetId = splitRev[1];
var node;
while ((node = toVisit.pop())) {
if (node.pos === targetPos && node.ids[0] === targetId) {
return true;
}
var branche... | javascript | {
"resource": ""
} |
q20312 | matchesSelector | train | function matchesSelector(doc, selector) {
/* istanbul ignore if */
if (typeof selector !== 'object') {
// match the CouchDB error message
throw 'Selector error: expected a JSON object';
}
selector = massageSelector(selector);
var row = {
'doc': doc
};
var rowsMatched = filterInMemoryFields([... | javascript | {
"resource": ""
} |
q20313 | invalidIdError | train | function invalidIdError(id) {
var err;
if (!id) {
err = pouchdbErrors.createError(pouchdbErrors.MISSING_ID);
} else if (typeof id !== 'string') {
err = pouchdbErrors.createError(pouchdbErrors.INVALID_ID);
} else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
err = pouchdbErrors.createError(p... | javascript | {
"resource": ""
} |
q20314 | deprecate | train | function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
c... | javascript | {
"resource": ""
} |
q20315 | train | function( el, props ) {
var key, pkey;
for ( key in props ) {
if ( props.hasOwnProperty( key ) ) {
pkey = pfx( key );
if ( pkey !== null ) {
el.style[ pkey ] = props[ key ];
}
}
}
return el;
} | javascript | {
"resource": ""
} | |
q20316 | train | function( currentStep, nextStep ) {
if ( lastEntered === currentStep ) {
lib.util.triggerEvent( currentStep, "impress:stepleave", { next: nextStep } );
lastEntered = null;
}
} | javascript | {
"resource": ""
} | |
q20317 | train | function( rootId ) { //jshint ignore:line
var lib = {};
for ( var libname in libraryFactories ) {
if ( libraryFactories.hasOwnProperty( libname ) ) {
if ( lib[ libname ] !== undefined ) {
throw "impress.js ERROR: Two libraries both tried to use libname: " ... | javascript | {
"resource": ""
} | |
q20318 | train | function( root ) { //jshint ignore:line
for ( var i = 0; i < preInitPlugins.length; i++ ) {
var thisLevel = preInitPlugins[ i ];
if ( thisLevel !== undefined ) {
for ( var j = 0; j < thisLevel.length; j++ ) {
thisLevel[ j ]( root );
}
... | javascript | {
"resource": ""
} | |
q20319 | train | function( target, type, listenerFunction ) {
eventListenerList.push( { target:target, type:type, listener:listenerFunction } );
} | javascript | {
"resource": ""
} | |
q20320 | train | function( target, type, listenerFunction ) {
target.addEventListener( type, listenerFunction );
pushEventListener( target, type, listenerFunction );
} | javascript | {
"resource": ""
} | |
q20321 | train | function( el, eventName, detail ) {
var event = document.createEvent( "CustomEvent" );
event.initCustomEvent( eventName, true, true, detail );
el.dispatchEvent( event );
} | javascript | {
"resource": ""
} | |
q20322 | train | function( event ) {
var step = event.target;
currentStepTimeout = util.toNumber( step.dataset.autoplay, autoplayDefault );
if ( status === "paused" ) {
setAutoplayTimeout( 0 );
} else {
setAutoplayTimeout( currentStepTimeout );
}
} | javascript | {
"resource": ""
} | |
q20323 | train | function() {
if ( consoleWindow ) {
// Set notes to next steps notes.
var newNotes = document.querySelector( '.active' ).querySelector( '.notes' );
if ( newNotes ) {
newNotes = newNotes.innerHTML;
} else {
... | javascript | {
"resource": ""
} | |
q20324 | train | function() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = '';
if ( lang.useAMPM ) {
ampm = ( hours < 12 ) ? 'AM' : 'PM';
hours = ( hour... | javascript | {
"resource": ""
} | |
q20325 | train | function() {
stepids = [];
var steps = root.querySelectorAll( ".step" );
for ( var i = 0; i < steps.length; i++ )
{
stepids[ i + 1 ] = steps[ i ].id;
}
} | javascript | {
"resource": ""
} | |
q20326 | train | function( index ) {
var id = "impress-toolbar-group-" + index;
if ( !groups[ index ] ) {
groups[ index ] = document.createElement( "span" );
groups[ index ].id = id;
var nextIndex = getNextGroupIndex( index );
if ( nextIndex === undefined ) {
... | javascript | {
"resource": ""
} | |
q20327 | sendMsg | train | function sendMsg(type, data) {
if (
typeof self !== 'undefined' &&
(typeof WorkerGlobalScope === 'undefined' ||
!(self instanceof WorkerGlobalScope))
) {
self.postMessage(
{
type: `webpack${type}`,
data,
},
'*'
);
}
} | javascript | {
"resource": ""
} |
q20328 | removeExportAnnotationsFromComment | train | function removeExportAnnotationsFromComment(comment) {
// Remove @export annotations.
comment = comment.replace(EXPORT_REGEX, '')
// Split into lines, remove empty comment lines, then recombine.
comment = comment.split('\n')
.filter(function(line) { return !/^ *\*? *$/.test(line); })
.join('\n');
... | javascript | {
"resource": ""
} |
q20329 | getAllExpressionStatements | train | function getAllExpressionStatements(node) {
console.assert(node.body && node.body.body);
var expressionStatements = [];
node.body.body.forEach(function(childNode) {
if (childNode.type == 'ExpressionStatement') {
expressionStatements.push(childNode);
} else if (childNode.body) {
var childExpres... | javascript | {
"resource": ""
} |
q20330 | createExternsFromConstructor | train | function createExternsFromConstructor(className, constructorNode) {
// Example code:
//
// /** @interface @exportInterface */
// FooLike = function() {};
//
// /** @exportInterface @type {number} */
// FooLike.prototype.bar;
//
// /** @constructor @export @implements {FooLike} */
// Foo = function()... | javascript | {
"resource": ""
} |
q20331 | train | function(val) {
switch (typeof val) {
case 'undefined':
case 'boolean':
case 'number':
case 'string':
case 'symbol':
case 'function':
return val;
case 'object':
default: {
// typeof null === 'object'
if (!val) return val... | javascript | {
"resource": ""
} | |
q20332 | getAdjustedTime | train | function getAdjustedTime(stream, time) {
if (!stream) return null;
const idx = stream.findSegmentPosition(time - period.startTime);
if (idx == null) return null;
const ref = stream.getSegmentReference(idx);
if (!ref) return null;
const refTime = ref.startTime + period.startTime;
goog.asserts... | javascript | {
"resource": ""
} |
q20333 | allUsableBrowserLaunchers | train | function allUsableBrowserLaunchers(config) {
var browsers = [];
// Load all launcher plugins.
// The format of the items in this list is something like:
// {
// 'launcher:foo1': ['type', Function],
// 'launcher:foo2': ['type', Function],
// }
// Where the launchers grouped together into one item we... | javascript | {
"resource": ""
} |
q20334 | onInstall | train | function onInstall(event) {
const preCacheApplication = async () => {
const cache = await caches.open(CACHE_NAME);
// Fetching these with addAll fails for CORS-restricted content, so we use
// fetchAndCache with no-cors mode to work around it.
// Optional resources: failure on these will NOT fail the... | javascript | {
"resource": ""
} |
q20335 | onActivate | train | function onActivate(event) {
// Delete old caches to save space.
const dropOldCaches = async () => {
const cacheNames = await caches.keys();
// Return true on all the caches we want to clean up.
// Note that caches are shared across the origin, so only remove
// caches we are sure we created.
c... | javascript | {
"resource": ""
} |
q20336 | onFetch | train | function onFetch(event) {
// Make sure this is a request we should be handling in the first place.
// If it's not, it's important to leave it alone and not call respondWith.
let useCache = false;
for (const prefix of CACHEABLE_URL_PREFIXES) {
if (event.request.url.startsWith(prefix)) {
useCache = true... | javascript | {
"resource": ""
} |
q20337 | fetchCacheableResource | train | async function fetchCacheableResource(request) {
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(request);
if (!navigator.onLine) {
// We are offline, and we know it. Just return the cached response, to
// avoid a bunch of pointless errors in the JS console that wil... | javascript | {
"resource": ""
} |
q20338 | fetchAndCache | train | async function fetchAndCache(cache, request) {
const response = await fetch(request);
cache.put(request, response.clone());
return response;
} | javascript | {
"resource": ""
} |
q20339 | timeout | train | function timeout(seconds, asyncProcess) {
return Promise.race([
asyncProcess,
new Promise(function(_, reject) {
setTimeout(reject, seconds * 1000);
}),
]);
} | javascript | {
"resource": ""
} |
q20340 | ShakaReceiver | train | function ShakaReceiver() {
/** @private {HTMLMediaElement} */
this.video_ = null;
/** @private {shaka.Player} */
this.player_ = null;
/** @private {shaka.cast.CastReceiver} */
this.receiver_ = null;
/** @private {Element} */
this.controlsElement_ = null;
/** @private {?number} */
this.controlsTi... | javascript | {
"resource": ""
} |
q20341 | alasql | train | function alasql(sql,params,cb){
params = params||[];
// Avoid setting params if not needed even with callback
if(typeof params === 'function'){
scope = cb;
cb = params;
params = [];
}
if(typeof params !== 'object'){
params = [params];
}
// Increase last request id
var id = alasql.lastid++;
/... | javascript | {
"resource": ""
} |
q20342 | hstyle | train | function hstyle(st) {
// Prepare string
var s = '';
for (var key in st) {
s += '<' + key;
for (var attr in st[key]) {
s += ' ';
if (attr.substr(0, 2) == 'x:') {
s += attr;
} else {
s += 'ss:';
}
s += attr + '="' + st[key][attr] + '"';
}
s += '/>';
}
v... | javascript | {
"resource": ""
} |
q20343 | execute | train | function execute(sql, params) {
if (0 === sql.trim().length) {
console.error("\nNo SQL to process\n");
yargs.showHelp();
process.exit(1);
}
for (var i = 1; i < params.length; i++) {
var a = params[i];
if (a[0] !== '"' && a[0] !== "'") {
if (+a == a) { // jshint ignore:line
params[i] = +a;
}
}... | javascript | {
"resource": ""
} |
q20344 | isDirectory | train | function isDirectory(filePath) {
var isDir = false;
try {
var absolutePath = path.resolve(filePath);
isDir = fs.lstatSync(absolutePath).isDirectory();
} catch (e) {
isDir = e.code === 'ENOENT';
}
return isDir;
} | javascript | {
"resource": ""
} |
q20345 | pack | train | function pack(items) {
var data = arguments,
idx = 0,
buffer,
bufferSize = 0;
// Calculate buffer size
items = items.split('');
items.forEach(function(type) {
if (type == 'v') {
bufferSize += 2;
} else if (type == 'V' || type == 'l') {
bufferSize += 4;
}
});
// Fill buffer
buff... | javascript | {
"resource": ""
} |
q20346 | xmlparse | train | function xmlparse(xml) {
xml = xml.trim();
// strip comments
xml = xml.replace(/<!--[\s\S]*?-->/g, '');
return document();
/**
* XML document.
*/
function document() {
return {
declaration: declaration(),
root: tag(),
};
}
/**
* Declaration.
*/
function declaration() {
var m = match(/... | javascript | {
"resource": ""
} |
q20347 | match | train | function match(re) {
var m = xml.match(re);
if (!m) return;
xml = xml.slice(m[0].length);
return m;
} | javascript | {
"resource": ""
} |
q20348 | extend | train | function extend(destination, source) {
for (var prop in source)
if (source.hasOwnProperty(prop))
destination[prop] = source[prop];
} | javascript | {
"resource": ""
} |
q20349 | findVertex | train | function findVertex(name) {
var objects = alasql.databases[alasql.useid].objects;
for (var k in objects) {
if (objects[k].name === name) {
return objects[k];
}
}
return undefined;
} | javascript | {
"resource": ""
} |
q20350 | queryfn | train | function queryfn(query, oldscope, cb, A, B) {
var aaa = query.sources.length;
var ms;
query.sourceslen = query.sources.length;
var slen = query.sourceslen;
query.query = query; // TODO Remove to prevent memory leaks
query.A = A;
query.B = B;
query.cb = cb;
query.oldscope = oldscope;
// Run all s... | javascript | {
"resource": ""
} |
q20351 | createAndOpenWallet | train | async function createAndOpenWallet(actor) {
const walletConfig = {"id": actor + ".wallet"}
const walletCredentials = {"key": actor + ".wallet_key"}
await indy.createWallet(walletConfig, walletCredentials)
return await indy.openWallet(walletConfig, walletCredentials)
} | javascript | {
"resource": ""
} |
q20352 | createAndOpenPoolHandle | train | async function createAndOpenPoolHandle(actor) {
const poolName = actor + "-pool-sandbox"
const poolGenesisTxnPath = await util.getPoolGenesisTxnPath(poolName)
const poolConfig = {"genesis_txn": poolGenesisTxnPath}
await indy.createPoolLedgerConfig(poolName, poolConfig)
.catch(e => {
... | javascript | {
"resource": ""
} |
q20353 | postRevocRegDefRequestToLedger | train | async function postRevocRegDefRequestToLedger(poolHandle, wallet, did, revRegDef) {
const revocRegRequest = await indy.buildRevocRegDefRequest(did, revRegDef)
await ensureSignAndSubmitRequest(poolHandle, wallet, did, revocRegRequest)
} | javascript | {
"resource": ""
} |
q20354 | renderLinks | train | function renderLinks() {
if ($("meta[property='docfx:newtab']").attr("content") === "true") {
$(document.links).filter(function () {
return this.hostname !== window.location.hostname;
}).attr('target', '_blank');
}
} | javascript | {
"resource": ""
} |
q20355 | highlight | train | function highlight() {
$('pre code').each(function (i, block) {
hljs.highlightBlock(block);
});
$('pre code[highlight-lines]').each(function (i, block) {
if (block.innerHTML === "") return;
var lines = block.innerHTML.split('\n');
queryString = block.getAttribute('highlight-lines');... | javascript | {
"resource": ""
} |
q20356 | renderSearchBox | train | function renderSearchBox() {
autoCollapse();
$(window).on('resize', autoCollapse);
$(document).on('click', '.navbar-collapse.in', function (e) {
if ($(e.target).is('a')) {
$(this).collapse('hide');
}
});
function autoCollapse() {
var navbar = $('#autocoll... | javascript | {
"resource": ""
} |
q20357 | highlightKeywords | train | function highlightKeywords() {
var q = url('?q');
if (q !== null) {
var keywords = q.split("%20");
keywords.forEach(function (keyword) {
if (keyword !== "") {
$('.data-searchable *').mark(keyword);
$('article *').mark(keyword);
}
});
... | javascript | {
"resource": ""
} |
q20358 | train | function (config) {
var builder = new lunr.Builder
builder.pipeline.add(
lunr.trimmer,
lunr.stopWordFilter,
lunr.stemmer
)
builder.searchPipeline.add(
lunr.stemmer
)
config.call(builder, builder)
return builder.build()
} | javascript | {
"resource": ""
} | |
q20359 | isPopover | train | function isPopover() {
var toPopover = false;
if (!p.params.convertToPopover && !p.params.onlyInPopover) return toPopover;
if (!p.inline && p.params.input) {
if (p.params.onlyInPopover) toPopover = true;
else {
if ($.device.ios) {
... | javascript | {
"resource": ""
} |
q20360 | each | train | function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
... | javascript | {
"resource": ""
} |
q20361 | deprecate | train | function deprecate(method, name, message) {
var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
return function() {
var e = new Error('get-stack-trace');
var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
... | javascript | {
"resource": ""
} |
q20362 | boolOrFn | train | function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
} | javascript | {
"resource": ""
} |
q20363 | addEventListeners | train | function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
} | javascript | {
"resource": ""
} |
q20364 | removeEventListeners | train | function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
} | javascript | {
"resource": ""
} |
q20365 | inArray | train | function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
return i;
}
... | javascript | {
"resource": ""
} |
q20366 | Input | train | function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget;
// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled th... | javascript | {
"resource": ""
} |
q20367 | computeIntervalInputData | train | function computeIntervalInputData(session, input) {
var last = session.lastInterval || input,
deltaTime = input.timeStamp - last.timeStamp,
velocity, velocityX, velocityY, direction;
if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
... | javascript | {
"resource": ""
} |
q20368 | simpleCloneInputData | train | function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i... | javascript | {
"resource": ""
} |
q20369 | getCenter | train | function getCenter(pointers) {
var pointersLength = pointers.length;
// no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0, y = 0, i = 0;
while (i < pointer... | javascript | {
"resource": ""
} |
q20370 | getScale | train | function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
} | javascript | {
"resource": ""
} |
q20371 | MouseInput | train | function MouseInput() {
this.evEl = MOUSE_ELEMENT_EVENTS;
this.evWin = MOUSE_WINDOW_EVENTS;
this.pressed = false; // mousedown state
Input.apply(this, arguments);
} | javascript | {
"resource": ""
} |
q20372 | PointerEventInput | train | function PointerEventInput() {
this.evEl = POINTER_ELEMENT_EVENTS;
this.evWin = POINTER_WINDOW_EVENTS;
Input.apply(this, arguments);
this.store = (this.manager.session.pointerEvents = []);
} | javascript | {
"resource": ""
} |
q20373 | PEhandler | train | function PEhandler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
... | javascript | {
"resource": ""
} |
q20374 | SingleTouchInput | train | function SingleTouchInput() {
this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
this.started = false;
Input.apply(this, arguments);
} | javascript | {
"resource": ""
} |
q20375 | Recognizer | train | function Recognizer(options) {
this.options = assign({}, this.defaults, options || {});
this.id = uniqueId();
this.manager = null;
// default is enable true
this.options.enable = ifUndefined(this.options.enable, true);
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requir... | javascript | {
"resource": ""
} |
q20376 | train | function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
... | javascript | {
"resource": ""
} | |
q20377 | train | function() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
} | javascript | {
"resource": ""
} | |
q20378 | train | function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign({}, inputData);
// is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
... | javascript | {
"resource": ""
} | |
q20379 | stateStr | train | function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
} | javascript | {
"resource": ""
} |
q20380 | directionStr | train | function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '... | javascript | {
"resource": ""
} |
q20381 | getRecognizerByNameIfManager | train | function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
} | javascript | {
"resource": ""
} |
q20382 | train | function(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input);
// on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType... | javascript | {
"resource": ""
} | |
q20383 | Hammer | train | function Hammer(element, options) {
options = options || {};
options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
return new Manager(element, options);
} | javascript | {
"resource": ""
} |
q20384 | train | function(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event == recognizer) {
return recognizers[i];
... | javascript | {
"resource": ""
} | |
q20385 | train | function(recognizer) {
if (invokeArrayArg(recognizer, 'add', this)) {
return this;
}
// remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
... | javascript | {
"resource": ""
} | |
q20386 | train | function(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
}
// no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) ... | javascript | {
"resource": ""
} | |
q20387 | generateDependenciesFiles | train | function generateDependenciesFiles ({ suffix, factories, entryFolder }) {
const braceOpen = '{' // a hack to be able to create a single brace open character in handlebars
// a map containing:
// {
// 'sqrt': true,
// 'subset': true,
// ...
// }
const exists = {}
Object.keys(factories).forEach(f... | javascript | {
"resource": ""
} |
q20388 | _deepFlatten | train | function _deepFlatten (nestedObject, flattenedObject) {
for (const prop in nestedObject) {
if (nestedObject.hasOwnProperty(prop)) {
const value = nestedObject[prop]
if (typeof value === 'object' && value !== null) {
_deepFlatten(value, flattenedObject)
} else {
flattenedObject[pr... | javascript | {
"resource": ""
} |
q20389 | zeros | train | function zeros (length) {
const arr = []
for (let i = 0; i < length; i++) {
arr.push(0)
}
return arr
} | javascript | {
"resource": ""
} |
q20390 | findIndex | train | function findIndex (array, item) {
return array
.map(function (i) {
return i.toLowerCase()
})
.indexOf(item.toLowerCase())
} | javascript | {
"resource": ""
} |
q20391 | validateOption | train | function validateOption (options, name, values) {
if (options[name] !== undefined && !contains(values, options[name])) {
const index = findIndex(values, options[name])
if (index !== -1) {
// right value, wrong casing
// TODO: lower case values are deprecated since v3, remove this warning some day.... | javascript | {
"resource": ""
} |
q20392 | unitFactory | train | function unitFactory (name, valueStr, unitStr) {
const dependencies = ['config', 'Unit', 'BigNumber']
return factory(name, dependencies, ({ config, Unit, BigNumber }) => {
// Note that we can parse into number or BigNumber.
// We do not parse into Fractions as that doesn't make sense: we would lose precisi... | javascript | {
"resource": ""
} |
q20393 | numberFactory | train | function numberFactory (name, value) {
const dependencies = ['config', 'BigNumber']
return factory(name, dependencies, ({ config, BigNumber }) => {
return config.number === 'BigNumber'
? new BigNumber(value)
: value
})
} | javascript | {
"resource": ""
} |
q20394 | addDeprecatedFunctions | train | function addDeprecatedFunctions (done) {
const code = String(fs.readFileSync(COMPILED_MAIN_ANY))
const updatedCode = code + '\n\n' +
'exports[\'var\'] = exports.deprecatedVar;\n' +
'exports[\'typeof\'] = exports.deprecatedTypeof;\n' +
'exports[\'eval\'] = exports.deprecatedEval;\n' +
'exports[\'imp... | javascript | {
"resource": ""
} |
q20395 | _forEach | train | function _forEach (array, callback) {
// figure out what number of arguments the callback function expects
const args = maxArgumentCount(callback)
const recurse = function (value, index) {
if (Array.isArray(value)) {
forEachArray(value, function (child, i) {
// we create a copy of the index arr... | javascript | {
"resource": ""
} |
q20396 | _validate | train | function _validate (array, size, dim) {
let i
const len = array.length
if (len !== size[dim]) {
throw new DimensionError(len, size[dim])
}
if (dim < size.length - 1) {
// recursively validate each child array
const dimNext = dim + 1
for (i = 0; i < len; i++) {
const child = array[i]
... | javascript | {
"resource": ""
} |
q20397 | _resize | train | function _resize (array, size, dim, defaultValue) {
let i
let elem
const oldLen = array.length
const newLen = size[dim]
const minLen = Math.min(oldLen, newLen)
// apply new length
array.length = newLen
if (dim < size.length - 1) {
// non-last dimension
const dimNext = dim + 1
// resize ex... | javascript | {
"resource": ""
} |
q20398 | _reshape | train | function _reshape (array, sizes) {
// testing if there are enough elements for the requested shape
let tmpArray = array
let tmpArray2
// for each dimensions starting by the last one and ignoring the first one
for (let sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
const size = sizes[sizeIndex... | javascript | {
"resource": ""
} |
q20399 | _squeeze | train | function _squeeze (array, dims, dim) {
let i, ii
if (dim < dims) {
const next = dim + 1
for (i = 0, ii = array.length; i < ii; i++) {
array[i] = _squeeze(array[i], dims, next)
}
} else {
while (Array.isArray(array)) {
array = array[0]
}
}
return array
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.