_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 = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
}
}
}
|
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);
}
}
return conflicts;
}
|
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 revs;
}
|
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 ? node.history.slice() : [];
history.push({id: id, opts: opts});
if (isLeaf) {
paths.push({pos: (pos + 1 - history.length), ids: history});
}
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], history: history});
}
}
return paths.reverse();
}
|
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;
}
}
return root;
}
|
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].status === 'available' ||
tree2[1].status === 'available') ? 'available' : 'missing';
}
for (var i = 0; i < tree2[2].length; i++) {
if (!tree1[2][0]) {
conflicts = 'new_leaf';
tree1[2][0] = tree2[2][i];
continue;
}
var merged = false;
for (var j = 0; j < tree1[2].length; j++) {
if (tree1[2][j][0] === tree2[2][i][0]) {
queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
merged = true;
}
}
if (!merged) {
conflicts = 'new_branch';
insertSorted(tree1[2], tree2[2][i], compareTree);
}
}
}
return {conflicts: conflicts, tree: in_tree1};
}
|
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 to, and generate a new set of flat trees
var path = paths[i];
var stemmed = path.ids;
var node;
if (stemmed.length > depth) {
// only do the stemming work if we actually need to stem
if (!stemmedRevs) {
stemmedRevs = {}; // avoid allocating this object unnecessarily
}
var numStemmed = stemmed.length - depth;
node = {
pos: path.pos + numStemmed,
ids: pathToTree(stemmed, numStemmed)
};
for (var s = 0; s < numStemmed; s++) {
var rev = (path.pos + s) + '-' + stemmed[s].id;
stemmedRevs[rev] = true;
}
} else { // no need to actually stem
node = {
pos: path.pos,
ids: pathToTree(stemmed, 0)
};
}
// Then we remerge all those flat trees together, ensuring that we dont
// connect trees that would go beyond the depth limit
if (result) {
result = doMerge(result, node, true).tree;
} else {
result = [node];
}
}
// this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
if (stemmedRevs) {
traverseRevTree(result, function (isLeaf, pos, revHash) {
// some revisions may have been removed in a branch but not in another
delete stemmedRevs[pos + '-' + revHash];
});
}
return {
tree: result,
revs: stemmedRevs ? Object.keys(stemmedRevs) : []
};
}
|
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 branches = node.ids[2];
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: node.pos + 1, ids: branches[i]});
}
}
return false;
}
|
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([row], { 'selector': selector }, Object.keys(selector));
return rowsMatched && rowsMatched.length === 1;
}
|
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(pouchdbErrors.RESERVED_ID);
}
if (err) {
throw err;
}
}
|
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 {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
|
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: " + libname;
}
lib[ libname ] = libraryFactories[ libname ]( rootId );
}
}
return lib;
}
|
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 {
newNotes = lang.noNotes;
}
consoleWindow.document.getElementById( 'notes' ).innerHTML = newNotes;
// Set the views
var baseURL = document.URL.substring( 0, document.URL.search( '#/' ) );
var slideSrc = baseURL + '#' + document.querySelector( '.active' ).id;
var preSrc = baseURL + '#' + nextStep().id;
var slideView = consoleWindow.document.getElementById( 'slideView' );
// Setting them when they are already set causes glithes in Firefox, so check first:
if ( slideView.src !== slideSrc ) {
slideView.src = slideSrc;
}
var preView = consoleWindow.document.getElementById( 'preView' );
if ( preView.src !== preSrc ) {
preView.src = preSrc;
}
consoleWindow.document.getElementById( 'status' ).innerHTML =
'<span class="moving">' + lang.moving + '</span>';
}
}
|
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 = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours === 0 ) ? 12 : hours;
}
// Clock
var clockStr = zeroPad( hours ) + ':' + zeroPad( minutes ) + ':' + zeroPad( seconds ) +
' ' + ampm;
consoleWindow.document.getElementById( 'clock' ).firstChild.nodeValue = clockStr;
// Timer
seconds = Math.floor( ( now - consoleWindow.timerStart ) / 1000 );
minutes = Math.floor( seconds / 60 );
seconds = Math.floor( seconds % 60 );
consoleWindow.document.getElementById( 'timer' ).firstChild.nodeValue =
zeroPad( minutes ) + 'm ' + zeroPad( seconds ) + 's';
if ( !consoleWindow.initialized ) {
// Nudge the slide windows after load, or they will scrolled wrong on Firefox.
consoleWindow.document.getElementById( 'slideView' ).contentWindow.scrollTo( 0, 0 );
consoleWindow.document.getElementById( 'preView' ).contentWindow.scrollTo( 0, 0 );
consoleWindow.initialized = true;
}
}
|
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 ) {
toolbar.appendChild( groups[ index ] );
} else {
toolbar.insertBefore( groups[ index ], groups[ nextIndex ] );
}
}
return groups[ index ];
}
|
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');
return comment;
}
|
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 childExpressions = getAllExpressionStatements(childNode);
expressionStatements.push.apply(expressionStatements, childExpressions);
}
});
return expressionStatements;
}
|
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() {
// /** @override @exportInterface */
// this.bar = 10;
// };
//
// Example externs:
//
// /**
// * Generated by createExternFromExportNode:
// * @constructor @implements {FooLike}
// */
// Foo = function() {}
//
// /**
// * Generated by createExternsFromConstructor:
// * @override
// */
// Foo.prototype.bar;
var expressionStatements = getAllExpressionStatements(constructorNode);
var externString = '';
expressionStatements.forEach(function(statement) {
var left = statement.expression.left;
var right = statement.expression.right;
// Skip anything that isn't an assignment to a member of "this".
if (statement.expression.type != 'AssignmentExpression' ||
left.type != 'MemberExpression' ||
left.object.type != 'ThisExpression')
return;
console.assert(left);
console.assert(right);
// Skip anything that isn't exported.
var comment = getLeadingBlockComment(statement);
if (!EXPORT_REGEX.test(comment))
return;
comment = removeExportAnnotationsFromComment(comment);
console.assert(left.property.type == 'Identifier');
var name = className + '.prototype.' + left.property.name;
externString += comment + '\n' + name + ';\n';
});
return externString;
}
|
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;
// This covers Uint8Array and friends, even without a TypedArray
// base-class constructor.
const isTypedArray =
val.buffer && val.buffer.constructor == ArrayBuffer;
if (isTypedArray) {
return val;
}
if (seenObjects.has(val)) {
return null;
}
const isArray = val.constructor == Array;
if (val.constructor != Object && !isArray) {
return null;
}
seenObjects.add(val);
const ret = isArray ? [] : {};
// Note |name| will equal a number for arrays.
for (const name in val) {
ret[name] = clone(val[name]);
}
// Length is a non-enumerable property, but we should copy it over in
// case it is not the default.
if (isArray) {
ret.length = val.length;
}
return ret;
}
}
}
|
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.assert(refTime <= time, 'Segment should start before time');
return refTime;
}
|
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 were defined by a single
// plugin, and the Functions in the inner array are the constructors for those
// launchers.
var plugins = require('karma/lib/plugin').resolve(['karma-*-launcher']);
plugins.forEach(function(map) {
Object.keys(map).forEach(function(name) {
// Launchers should all start with 'launcher:', but occasionally we also
// see 'test' come up for some reason.
if (!name.startsWith('launcher:')) return;
var browserName = name.split(':')[1];
var pluginConstructor = map[name][1];
// Most launchers requiring configuration through customLaunchers have
// no DEFAULT_CMD. Some launchers have DEFAULT_CMD, but not for this
// platform. Finally, WebDriver has DEFAULT_CMD, but still requires
// configuration, so we simply blacklist it by name.
var DEFAULT_CMD = pluginConstructor.prototype.DEFAULT_CMD;
if (!DEFAULT_CMD || !DEFAULT_CMD[process.platform]) return;
if (browserName == 'WebDriver') return;
// Now that we've filtered out the browsers that can't be launched without
// custom config or that can't be launched on this platform, we filter out
// the browsers you don't have installed.
var ENV_CMD = pluginConstructor.prototype.ENV_CMD;
var browserPath = process.env[ENV_CMD] || DEFAULT_CMD[process.platform];
if (!fs.existsSync(browserPath) &&
!which.sync(browserPath, {nothrow: true})) return;
browsers.push(browserName);
});
});
// Once we've found the names of all the standard launchers, add to that list
// the names of any custom launcher configurations.
if (config.customLaunchers) {
browsers.push.apply(browsers, Object.keys(config.customLaunchers));
}
return browsers;
}
|
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 Promise chain.
// We will also not wait for them to be installed.
for (const url of OPTIONAL_RESOURCES) {
const request = new Request(url, {mode: 'no-cors'});
fetchAndCache(cache, request).catch(() => {});
}
// Critical resources: failure on these will fail the Promise chain.
// The installation will not be complete until these are all cached.
const criticalFetches = [];
for (const url of CRITICAL_RESOURCES) {
const request = new Request(url, {mode: 'no-cors'});
criticalFetches.push(fetchAndCache(cache, request));
}
return Promise.all(criticalFetches);
};
event.waitUntil(preCacheApplication());
}
|
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.
const cleanTheseUp = cacheNames.filter((cacheName) =>
cacheName.startsWith(CACHE_NAME_PREFIX) && cacheName != CACHE_NAME);
const cleanUpPromises =
cleanTheseUp.map((cacheName) => caches.delete(cacheName));
await Promise.all(cleanUpPromises);
};
event.waitUntil(dropOldCaches());
}
|
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;
break;
}
}
// Now we need to check our resource lists. The list of prefixes above won't
// cover everything that was installed initially, and those things still need
// to be read from cache. So we check if this request URL matches one of
// those lists.
// The resource lists contain some relative URLs and some absolute URLs. The
// check here will only be able to match the absolute ones, but that's enough,
// because the relative ones are covered by the loop above.
if (!useCache) {
if (CRITICAL_RESOURCES.includes(event.request.url) ||
OPTIONAL_RESOURCES.includes(event.request.url)) {
useCache = true;
}
}
if (useCache) {
event.respondWith(fetchCacheableResource(event.request));
}
}
|
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 will confuse
// us developers. If there is no cached response, this will just be a
// failed request.
return cachedResponse;
}
if (cachedResponse) {
// We have it in cache. Try to fetch a live version and update the cache,
// but limit how long we will wait for the updated version.
try {
return timeout(NETWORK_TIMEOUT, fetchAndCache(cache, request));
} catch (error) {
// We tried to fetch a live version, but it either failed or took too
// long. If it took too long, the fetch and cache operation will continue
// in the background. In both cases, we should go ahead with a cached
// version.
return cachedResponse;
}
} else {
// We should have this in cache, but we don't. Fetch and cache a fresh
// copy and then return it.
return fetchAndCache(cache, request);
}
}
|
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.controlsTimerId_ = null;
/** @private {Element} */
this.idle_ = null;
/** @private {?number} */
this.idleTimerId_ = null;
/**
* In seconds.
* @const
* @private {number}
*/
this.idleTimeout_ = 300;
}
|
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++;
// Save callback
alasql.buffer[id] = cb;
// Send a message to worker
alasql.webworker.postMessage({id:id,sql:sql,params:params});
}
|
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 += '/>';
}
var hh = hash(s);
// Store in hash
if (styles[hh]) {
} else {
styles[hh] = {styleid: stylesn};
s2 += '<Style ss:ID="s' + stylesn + '">';
s2 += s;
s2 += '</Style>';
stylesn++;
}
return 's' + styles[hh].styleid;
}
|
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;
}
}
}
alasql.promise(sql, params)
.then(function (res) {
if (!alasql.options.stdout) {
console.log(formatOutput(res));
}
process.exit(0);
}).catch(function (err) {
let errorJsonObj = JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
console.error(formatOutput({
error: errorJsonObj
}));
process.exit(1);
});
}
|
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
buffer = new Buffer(bufferSize);
items.forEach(function(type, index) {
if (type == 'v') {
buffer.writeUInt16LE(data[index + 1], idx);
idx += 2;
} else if (type == 'V') {
buffer.writeUInt32LE(data[index + 1], idx);
idx += 4;
} else if (type == 'l') {
buffer.writeInt32LE(data[index + 1], idx);
idx += 4;
}
});
return buffer;
}
|
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(/^<\?xml\s*/);
if (!m) return;
// tag
var node = {
attributes: {},
};
// attributes
while (!(eos() || is('?>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
match(/\?>\s*/);
return node;
}
/**
* Tag.
*/
function tag() {
var m = match(/^<([\w-:.]+)\s*/);
if (!m) return;
// name
var node = {
name: m[1],
attributes: {},
children: [],
};
// attributes
while (!(eos() || is('>') || is('?>') || is('/>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
// self closing tag
if (match(/^\s*\/>\s*/)) {
return node;
}
match(/\??>\s*/);
// content
node.content = content();
// children
var child;
while ((child = tag())) {
node.children.push(child);
}
// closing
match(/^<\/[\w-:.]+>\s*/);
return node;
}
/**
* Text content.
*/
function content() {
var m = match(/^([^<]*)/);
if (m) return m[1];
return '';
}
/**
* Attribute.
*/
function attribute() {
var m = match(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);
if (!m) return;
return {name: m[1], value: strip(m[2])};
}
/**
* Strip quotes from `val`.
*/
function strip(val) {
return val.replace(/^['"]|['"]$/g, '');
}
/**
* Match `re` and advance the string.
*/
function match(re) {
var m = xml.match(re);
if (!m) return;
xml = xml.slice(m[0].length);
return m;
}
/**
* End-of-source.
*/
function eos() {
return 0 == xml.length;
}
/**
* Check for `prefix`.
*/
function is(prefix) {
return 0 == xml.indexOf(prefix);
}
}
|
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 subqueries before main statement
if (query.queriesfn) {
query.sourceslen += query.queriesfn.length;
slen += query.queriesfn.length;
query.queriesdata = [];
// console.log(8);
query.queriesfn.forEach(function(q, idx) {
// if(query.explain) ms = Date.now();
//console.log(18,idx);
// var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query));
// var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query));
// console.log(A,B);
// console.log(q);
q.query.params = query.params;
// query.queriesdata[idx] =
// if(false) {
// queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query);
// } else {
queryfn2([], -idx - 1, query);
// }
// console.log(27,q);
// query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms});
// query.queriesdata[idx] = res;
// return res;
});
// console.log(9,query.queriesdata.length);
// console.log(query.queriesdata[0]);
}
var scope;
if (!oldscope) scope = {};
else scope = cloneDeep(oldscope);
query.scope = scope;
// First - refresh data sources
var result;
query.sources.forEach(function(source, idx) {
// source.data = query.database.tables[source.tableid].data;
// console.log(666,idx);
source.query = query;
var rs = source.datafn(query, query.params, queryfn2, idx, alasql);
// console.log(333,rs);
if (typeof rs !== 'undefined') {
// TODO - this is a hack: check if result is array - check all cases and
// make it more logical
if ((query.intofn || query.intoallfn) && Array.isArray(rs)) rs = rs.length;
result = rs;
}
//
// Ugly hack to use in query.wherefn and source.srcwherefns functions
// constructions like this.queriesdata['test'].
// I can elimite it with source.srcwherefn.bind(this)()
// but it may be slow.
//
source.queriesdata = query.queriesdata;
});
if (query.sources.length == 0 || 0 === slen) result = queryfn3(query);
// console.log(82,aaa,slen,query.sourceslen, query.sources.length);
return result;
}
|
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 => {
console.log("ERROR : ", e)
process.exit()
})
return await indy.openPoolLedger(poolName, poolConfig)
}
|
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');
if (!queryString) return;
var ranges = queryString.split(',');
for (var j = 0, range; range = ranges[j++];) {
var found = range.match(/^(\d+)\-(\d+)?$/);
if (found) {
// consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional
var start = +found[1];
var end = +found[2];
if (isNaN(end) || end > lines.length) {
end = lines.length;
}
} else {
// consider region as a sigine line number
if (isNaN(range)) continue;
var start = +range;
var end = start;
}
if (start <= 0 || end <= 0 || start > end || start > lines.length) {
// skip current region if invalid
continue;
}
lines[start - 1] = '<span class="line-highlight">' + lines[start - 1];
lines[end - 1] = lines[end - 1] + '</span>';
}
block.innerHTML = lines.join('\n');
});
}
|
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 = $('#autocollapse');
if (navbar.height() === null) {
setTimeout(autoCollapse, 300);
}
navbar.removeClass(collapsed);
if (navbar.height() > 60) {
navbar.addClass(collapsed);
}
}
}
|
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) {
toPopover = $.device.ipad ? true : false;
}
else {
if ($(window).width() >= 768) toPopover = true;
}
}
}
return toPopover;
}
|
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++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
|
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, '')
.replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
var log = window.console && (window.console.warn || window.console.log);
if (log) {
log.call(window.console, deprecationMessage, stack);
}
return method.apply(this, arguments);
};
}
|
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;
}
i++;
}
return -1;
}
}
|
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 the input events are completely bypassed.
this.domHandler = function(ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
|
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)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
|
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].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
|
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 < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
|
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;
var isTouch = (pointerType == INPUT_TYPE_TOUCH);
// get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId');
// start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
}
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
// update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
}
|
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.requireFail = [];
}
|
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]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
}
|
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])) {
this.reset();
this.state = STATE_FAILED;
return;
}
// reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone);
// the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(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 & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
}
|
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];
}
}
return null;
}
|
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);
recognizer.manager = this;
this.touchAction.update();
return 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) {
return;
}
data.type = event;
data.preventDefault = function() {
data.srcEvent.preventDefault();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
}
|
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(factoryName => {
const factory = factories[factoryName]
exists[factory.fn] = true
})
mkdirSyncIfNotExists(path.join(entryFolder, 'dependencies' + suffix))
const data = {
suffix,
factories: Object.keys(factories).map((factoryName) => {
const factory = factories[factoryName]
return {
suffix,
factoryName,
braceOpen,
name: getDependenciesName(factoryName, factories), // FIXME: rename name with dependenciesName, and functionName with name
fileName: './dependencies' + suffix + '/' + getDependenciesFileName(factoryName) + '.generated',
eslintComment: factoryName === 'createSQRT1_2'
? ' // eslint-disable-line camelcase'
: undefined,
dependencies: factory.dependencies
.map(stripOptionalNotation)
.filter(dependency => !IGNORED_DEPENDENCIES[dependency])
.filter(dependency => {
if (!exists[dependency]) {
if (factory.dependencies.indexOf(dependency) !== -1) {
throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
}
return false
}
return true
})
.map(dependency => {
const factoryName = findFactoryName(factories, dependency)
const name = getDependenciesName(factoryName, factories)
const fileName = './' + getDependenciesFileName(factoryName) + '.generated'
return {
suffix,
name,
fileName
}
})
}
})
}
// generate a file for every dependency
data.factories.forEach(factoryData => {
const generatedFactory = dependenciesFileTemplate(factoryData)
const p = path.join(entryFolder, factoryData.fileName + '.js')
fs.writeFileSync(p, generatedFactory)
})
// generate a file with links to all dependencies
const generated = dependenciesIndexTemplate(data)
fs.writeFileSync(path.join(entryFolder, 'dependencies' + suffix + '.generated.js'), generated)
}
|
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[prop] = value
}
}
}
}
|
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.
console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".')
options[name] = values[index] // change the option to the right casing
} else {
// unknown value
console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.')
}
}
}
|
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 precision of the values
// Therefore we dont use Unit.parse()
const value = config.number === 'BigNumber'
? new BigNumber(valueStr)
: parseFloat(valueStr)
const unit = new Unit(value, unitStr)
unit.fixPrefix = true
return unit
})
}
|
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[\'import\'] = exports.deprecatedImport;\n'
fs.writeFileSync(COMPILED_MAIN_ANY, updatedCode)
log('Added deprecated functions to ' + COMPILED_MAIN_ANY)
done()
}
|
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 array and append the new index value
recurse(child, index.concat(i))
})
} else {
// invoke the callback function with the right number of arguments
if (args === 1) {
callback(value)
} else if (args === 2) {
callback(value, index)
} else { // 3 or -1
callback(value, index, array)
}
}
}
recurse(array, [])
}
|
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]
if (!Array.isArray(child)) {
throw new DimensionError(size.length - 1, size.length, '<')
}
_validate(array[i], size, dimNext)
}
} else {
// last dimension. none of the childs may be an array
for (i = 0; i < len; i++) {
if (Array.isArray(array[i])) {
throw new DimensionError(size.length + 1, size.length, '>')
}
}
}
}
|
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 existing child arrays
for (i = 0; i < minLen; i++) {
// resize child array
elem = array[i]
if (!Array.isArray(elem)) {
elem = [elem] // add a dimension
array[i] = elem
}
_resize(elem, size, dimNext, defaultValue)
}
// create new child arrays
for (i = minLen; i < newLen; i++) {
// get child array
elem = []
array[i] = elem
// resize new child array
_resize(elem, size, dimNext, defaultValue)
}
} else {
// last dimension
// remove dimensions of existing values
for (i = 0; i < minLen; i++) {
while (Array.isArray(array[i])) {
array[i] = array[i][0]
}
}
// fill new elements with the default value
for (i = minLen; i < newLen; i++) {
array[i] = defaultValue
}
}
}
|
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]
tmpArray2 = []
// aggregate the elements of the current tmpArray in elements of the requested size
const length = tmpArray.length / size
for (let i = 0; i < length; i++) {
tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size))
}
// set it as the new tmpArray for the next loop turn or for return
tmpArray = tmpArray2
}
return tmpArray
}
|
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.