_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6500
|
train
|
function (callback) {
var self = this;
self.registration_callbacks.push(callback);
_.each(self.all_sockets(), function (socket) {
callback(socket);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6501
|
train
|
function(request /*, moreArguments */) {
// Store arguments for use within the closure below
var args = arguments;
// Rewrite /websocket and /websocket/ urls to /sockjs/websocket while
// preserving query string.
var parsedUrl = url.parse(request.url);
if (parsedUrl.pathname === pathPrefix + '/websocket' ||
parsedUrl.pathname === pathPrefix + '/websocket/') {
parsedUrl.pathname = self.prefix + '/websocket';
request.url = url.format(parsedUrl);
}
_.each(oldHttpServerListeners, function(oldListener) {
oldListener.apply(httpServer, args);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6502
|
add
|
train
|
function add(object) {
var args = Array.prototype.slice.call(arguments, 1);
//loop through all over the arguments
forEach(args, function(value, i) {
switch(typeof object) {
case 'object':
isArray(object)
? object.push(value)
: extend(object, isObject(value) ? value : creObject(i, value));
break;
case 'string':
object += isString(value) ? value : '';
break;
case 'number':
object += isNumber(value) ? value : 0;
}
});
return object;
}
|
javascript
|
{
"resource": ""
}
|
q6503
|
runInContext
|
train
|
function runInContext(context) {
// Node.js
return (typeof module === "object" && module && module.exports === context)
? module.exports = agile
// Browsers
: context[(context._) ? 'agile' : '_'] = agile;
}
|
javascript
|
{
"resource": ""
}
|
q6504
|
processIfValues
|
train
|
function processIfValues(css, result, rule, decl, queries) {
var query = null;
var re = /(.*)\s+(?:\?if|\?)\s+media\s+(.*)/;
var re2 = /\s/g;
var hash = null;
// Check if we're working with comments.
var match = decl.value ? decl.value.match(re) : decl.text.match(re);
// console.log(match)
if(match && match[1] && match[2]) {
if(decl.value)
decl.value = match[1];
else
decl.text = match[1];
hash = match[2].replace(re2, '');
if(!queries[hash]) {
queries[hash] = {
arg: match[2],
sel: rule.selector,
props: []
}
}
queries[hash].props.push({name: decl.prop, value: match[1], query: match[2], hash: hash, decl: decl});
}
else
decl.warn(result, 'Appears to be a malformed `?if media` query -> ' + decl);
}
|
javascript
|
{
"resource": ""
}
|
q6505
|
createAtRules
|
train
|
function createAtRules(css, rule, queries) {
var parent = rule.parent;
var prev = rule;
for(var k in queries) {
var q = queries[k];
var at = postcss.atRule({name: 'media', params: q.arg, source: rule.source});
var qr = postcss.rule ({selector: q.sel, source: rule.source});
at.append(qr);
for (var i = 0; i < q.props.length; i++) {
var prop = q.props[i];
qr.append(prop.decl.remove());
};
// Again we keep track of the previous insert and insert after it, to maintain the original order
// and CSS specificity.
parent.insertAfter(prev, at);
prev = at;
}
}
|
javascript
|
{
"resource": ""
}
|
q6506
|
getContent
|
train
|
function getContent() {
var h = pageInformation.response.headers || {};
if (/json/.test(h['content-type'])) {
try {
return JSON.parse(page.plainText);
}
catch (e) {
return page.content;
}
}
else {
return page.content;
}
}
|
javascript
|
{
"resource": ""
}
|
q6507
|
wrapFailure
|
train
|
function wrapFailure(reason) {
var res = {
fail: true,
url: page.url,
body: getContent(),
headers: pageInformation.response.headers,
status: pageInformation.response.status
};
if (reason)
res.reason = reason;
if (pageInformation.error)
res.error = pageInformation.error;
return res;
}
|
javascript
|
{
"resource": ""
}
|
q6508
|
wrapSuccess
|
train
|
function wrapSuccess(result) {
return {
url: page.url,
body: getContent(),
headers: pageInformation.response.headers,
status: pageInformation.response.status,
error: result.error ? helpers.serializeError(result.error) : null,
data: result.data
};
}
|
javascript
|
{
"resource": ""
}
|
q6509
|
train
|
function(status) {
// Page is now opened
pageInformation.isOpened = true;
pageInformation.status = status;
// Failing
if (status !== 'success') {
parent.replyTo(callId, wrapFailure('fail'));
return cleanup();
}
// Wrong status code
if (!pageInformation.response.status || pageInformation.response.status >= 400) {
parent.replyTo(callId, wrapFailure('status'));
return cleanup();
}
// Waiting for body to load
page.evaluateAsync(function() {
var interval = setInterval(function() {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
clearInterval(interval);
window.callPhantom({
head: 'documentReady',
body: true,
passphrase: 'detoo'
});
}
}, 30);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6510
|
processBlockContent
|
train
|
function processBlockContent (block, contentState, options) {
const entityModifiers = options.entityModifiers || {}
let text = block.getText()
// Cribbed from sstur’s implementation in draft-js-export-html
// https://github.com/sstur/draft-js-export-html/blob/master/src/stateToHTML.js#L222
let charMetaList = block.getCharacterList()
let entityPieces = getEntityRanges(text, charMetaList)
// Map over the block’s entities
const entities = entityPieces.map(([entityKey, stylePieces]) => {
let entity = entityKey ? contentState.getEntity(entityKey) : null
// Extract the inline element
const inline = stylePieces.map(([text, style]) => {
return [
'inline',
[
style.toJS().map((s) => s),
text,
],
]
})
// Nest within an entity if there’s data
if (entity) {
const type = entity.getType()
const mutability = entity.getMutability()
let data = entity.getData()
// Run the entity data through a modifier if one exists
const modifier = entityModifiers[type]
if (modifier) {
data = modifier(data)
}
return [
[
'entity',
[
type,
entityKey,
mutability,
data,
inline,
],
],
]
} else {
return inline
}
})
// Flatten the result
return entities.reduce((a, b) => {
return a.concat(b)
}, [])
}
|
javascript
|
{
"resource": ""
}
|
q6511
|
processBlocks
|
train
|
function processBlocks (blocks, contentState, options = {}) {
// Track block context
let context = context || []
let currentContext = context
let lastBlock = null
let lastProcessed = null
let parents = []
// Procedurally process individual blocks
blocks.forEach(processBlock)
/**
* Process an individual block
* @param {ContentBlock} block An individual ContentBlock instance
* @return {Array} A abstract syntax tree node representing a block and its
* children
*/
function processBlock (block) {
const type = block.getType()
const key = block.getKey()
const data = (block.getData) ? block.getData().toJS() : {}
const output = [
'block',
[
type,
key,
processBlockContent(block, contentState, options),
data,
],
]
// Push into context (or not) based on depth. This means either the top-level
// context array, or the `children` of a previous block
// This block is deeper
if (lastBlock && block.getDepth() > lastBlock.getDepth()) {
// Extract reference object from flat context
// parents.push(lastProcessed) // (mutating)
currentContext = lastProcessed[dataSchema.block.children]
} else if (lastBlock && block.getDepth() < lastBlock.getDepth() && block.getDepth() > 0) {
// This block is shallower (but not at the root). We want to find the last
// block that is one level shallower than this one to append it to
let parent = parents[block.getDepth() - 1]
currentContext = parent[dataSchema.block.children]
} else if (block.getDepth() === 0) {
// Reset the parent context if we reach the top level
parents = []
currentContext = context
}
currentContext.push(output)
lastProcessed = output[1]
// Store a reference to the last block at any given depth
parents[block.getDepth()] = lastProcessed
lastBlock = block
}
return context
}
|
javascript
|
{
"resource": ""
}
|
q6512
|
getBaseConfig
|
train
|
function getBaseConfig(isProd) {
// get library details from JSON config
var libraryDesc = require('./package.json').library;
var libraryEntryPoint = path.join('src', libraryDesc.entry);
// generate webpack base config
return {
entry: path.join(__dirname, libraryEntryPoint),
output: {
// ommitted - will be filled according to target env
},
module: {
preLoaders: [
{test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: "eslint-loader"}
],
loaders: [
{test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: "babel-loader"},
]
},
eslint: {
configFile: './.eslintrc'
},
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js']
},
devtool: isProd ? null : '#eval-source-map',
debug: !isProd,
plugins: isProd ? [
new webpack.DefinePlugin({'process.env': {'NODE_ENV': '"production"'}}),
new UglifyJsPlugin({ minimize: true })
// Prod plugins here
] : [
new webpack.DefinePlugin({'process.env': {'NODE_ENV': '"development"'}})
// Dev plugins here
]
};
}
|
javascript
|
{
"resource": ""
}
|
q6513
|
train
|
function (config) {
if (!config) {
config = {};
}
this.subject = config.subject;
this.value = config.value;
this.operator = (config.operator) ? config.operator : Operators.EQUALS;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6514
|
train
|
function () {
var self = this;
if (!self._waitingForQuiescence())
self._flushBufferedWrites();
_.each(self._stores, function (s) {
s.saveOriginals();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6515
|
train
|
function() {
var self = this;
if (_.isEmpty(self._outstandingMethodBlocks))
return;
_.each(self._outstandingMethodBlocks[0].methods, function (m) {
m.sendMessage();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6516
|
APIError
|
train
|
function APIError(message, type, field) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'APIError';
this.message = message;
this.type = type;
this.field = field;
}
|
javascript
|
{
"resource": ""
}
|
q6517
|
linkPackages
|
train
|
function linkPackages(dstPacksDir) {
if (!dstPacksDir) {
dstPacksDir = Path.resolve(rootDir, "packages");
}
else {
dstPacksDir = Path.resolve(cwd, dstPacksDir);
}
// Ensure destination dir
try {
Fs.mkdirSync(dstPacksDir);
}
catch (_) {}
var packNames = Fs.readdirSync(srcPacksDir);
// Ensure symlinks
packNames.forEach(function (packName) {
var dstPackDir = Path.resolve(dstPacksDir, packName);
var linkPath = Path.relative(dstPacksDir, Path.resolve(srcPacksDir, packName));
try {
Fs.symlinkSync(linkPath, dstPackDir);
}
catch (_) {}
});
console.log();
console.log("Packages have been successfully linked at:")
console.log();
console.log(" " + dstPacksDir);
console.log();
}
|
javascript
|
{
"resource": ""
}
|
q6518
|
Stream
|
train
|
function Stream(options) {
/**
* Whether or not the Stream was initialized as
* a single- or multi-key stream.
*
* @property multi
* @type Boolean
*/
reader(this, 'multi', !(options && options.apiKey));
if (!this.multi) {
options.headers = options.headers || {};
options.headers['Zotero-API-Key'] = options.apiKey;
delete options.apiKey;
}
Client.call(this, options);
/**
* @property retry
* @type Object
*/
reader(this, 'retry', {
delay: Stream.DEFAULT_RETRY
});
/**
* @property idle
* @type Object
*/
reader(this, 'idle', {
ping: Stream.IDLE_TIMEOUT,
pong: Stream.IDLE_TIMEOUT / 2
});
/**
* @property subscriptions
* @type Subscriptions
*/
this.subscriptions = new Subscriptions();
this.open = this.open.bind(this);
this.opened = this.opened.bind(this);
this.closed = this.closed.bind(this);
this.ping = this.ping.bind(this);
this.pong = this.pong.bind(this);
this.receive = this.receive.bind(this);
this.error = this.error.bind(this);
this.open();
}
|
javascript
|
{
"resource": ""
}
|
q6519
|
getRange
|
train
|
function getRange(sel) {
sel = sel || getSelection();
return sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
}
|
javascript
|
{
"resource": ""
}
|
q6520
|
setRange
|
train
|
function setRange(saved, sel) {
if (!saved) { return; }
// will make new selection, if unset
sel = sel || getSelection();
sel.removeAllRanges();
sel.addRange(saved);
}
|
javascript
|
{
"resource": ""
}
|
q6521
|
getRect
|
train
|
function getRect(sel) {
sel = sel || getSelection();
if (!sel.rangeCount) { return false; }
var range = sel.getRangeAt(0).cloneRange();
// on Webkit 'range.getBoundingClientRect()' sometimes return 0/0/0/0 - but 'range.getClientRects()' works
var rects = range.getClientRects ? range.getClientRects() : [];
for (var i = 0; i < rects.length; ++i) {
var rect = rects[i];
if (rect.left && rect.top && rect.right && rect.bottom) {
return {
// Modern browsers return floating-point numbers
left: parseInt(rect.left, 10),
top: parseInt(rect.top, 10),
width: parseInt(rect.right - rect.left, 10),
height: parseInt(rect.bottom - rect.top, 10)
};
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q6522
|
getNodes
|
train
|
function getNodes(sel) {
var range = getRange(sel);
if (!range) { return []; }
var node = range.startContainer;
var endNode = range.endContainer;
// Special case for a range that is contained within a single node
if (node === endNode) { return [node]; }
// Iterate nodes until we hit the end container
var nodes = [];
while (node && node !== endNode) {
nodes.push(node = nextNode(node));
}
// Add partially selected nodes at the start of the range
node = range.startContainer;
while (node && node !== range.commonAncestorContainer) {
nodes.unshift(node);
node = node.parentNode;
}
return nodes;
}
|
javascript
|
{
"resource": ""
}
|
q6523
|
getHTML
|
train
|
function getHTML(sel) {
sel = sel || getSelection();
if (!sel.rangeCount || sel.isCollapsed) { return null; }
var len = sel.rangeCount;
var container = doc.createElement('div');
for (var i = 0; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
return container.innerHTML;
}
|
javascript
|
{
"resource": ""
}
|
q6524
|
isWithin
|
train
|
function isWithin(container, sel) {
sel = sel || getSelection();
return container.contains(sel.anchorNode) && container.contains(sel.focusNode);
}
|
javascript
|
{
"resource": ""
}
|
q6525
|
getCaretWord
|
train
|
function getCaretWord(sel) {
sel = sel || getSelection();
var rng = getRange(sel);
expandToWord(sel);
var str = sel.toString(); // range?
// Restore selection
setRange(rng);
return str;
}
|
javascript
|
{
"resource": ""
}
|
q6526
|
isBackwards
|
train
|
function isBackwards(sel) {
sel = sel || getSelection();
if (isCollapsed(sel)) { return; }
// Detect if selection is backwards
var range = doc.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
range.detach();
// if `collapsed` then it's backwards
return range.collapsed;
}
|
javascript
|
{
"resource": ""
}
|
q6527
|
snapSelected
|
train
|
function snapSelected(sel) {
sel = sel || getSelection();
if (isCollapsed(sel)) { return; }
var end = sel.focusNode;
var off = sel.focusOffset;
var dir = ['forward', 'backward'];
isBackwards(sel) && dir.reverse();
// modify() works on the focus of the selection
sel.collapse(sel.anchorNode, sel.anchorOffset);
sel.modify('move', dir[0], 'character');
sel.modify('move', dir[1], 'word');
sel.extend(end, off);
sel.modify('extend', dir[1], 'character');
sel.modify('extend', dir[0], 'word');
}
|
javascript
|
{
"resource": ""
}
|
q6528
|
train
|
function () {
var self = this;
if (self === DDPServer._CurrentWriteFence.get())
throw Error("Can't arm the current fence");
self.armed = true;
self._maybeFire();
}
|
javascript
|
{
"resource": ""
}
|
|
q6529
|
train
|
function () {
var self = this;
var future = new Future;
self.onAllCommitted(function () {
future['return']();
});
self.arm();
future.wait();
}
|
javascript
|
{
"resource": ""
}
|
|
q6530
|
createNode
|
train
|
function createNode(el, attr) {
// html comment is not currently supported by virtual-dom
if (el.nodeType === 3) {
return createVirtualTextNode(el);
// cdata or doctype is not currently supported by virtual-dom
} else if (el.nodeType === 1 || el.nodeType === 9) {
return createVirtualDomNode(el, attr);
}
// default to empty text node
return new VText('');
}
|
javascript
|
{
"resource": ""
}
|
q6531
|
createVirtualDomNode
|
train
|
function createVirtualDomNode(el, attr) {
var ns = el.namespaceURI !== HTML_NAMESPACE ? el.namespaceURI : null;
var key = attr && el.getAttribute(attr) ? el.getAttribute(attr) : null;
return new VNode(
el.tagName
, createProperties(el)
, createChildren(el, attr)
, key
, ns
);
}
|
javascript
|
{
"resource": ""
}
|
q6532
|
createChildren
|
train
|
function createChildren(el, attr) {
var children = [];
for (var i = 0; i < el.childNodes.length; i++) {
children.push(createNode(el.childNodes[i], attr));
};
return children;
}
|
javascript
|
{
"resource": ""
}
|
q6533
|
createProperties
|
train
|
function createProperties(el) {
var properties = {};
if (!el.hasAttributes()) {
return properties;
}
var ns;
if (el.namespaceURI && el.namespaceURI !== HTML_NAMESPACE) {
ns = el.namespaceURI;
}
var attr;
for (var i = 0; i < el.attributes.length; i++) {
// use built in css style parsing
if(el.attributes[i].name == 'style'){
attr = createStyleProperty(el);
}
else if (ns) {
attr = createPropertyNS(el.attributes[i]);
} else {
attr = createProperty(el.attributes[i]);
}
// special case, namespaced attribute, use properties.foobar
if (attr.ns) {
properties[attr.name] = {
namespace: attr.ns
, value: attr.value
};
// special case, use properties.attributes.foobar
} else if (attr.isAttr) {
// init attributes object only when necessary
if (!properties.attributes) {
properties.attributes = {}
}
properties.attributes[attr.name] = attr.value;
// default case, use properties.foobar
} else {
properties[attr.name] = attr.value;
}
};
return properties;
}
|
javascript
|
{
"resource": ""
}
|
q6534
|
createProperty
|
train
|
function createProperty(attr) {
var name, value, isAttr;
// using a map to find the correct case of property name
if (propertyMap[attr.name]) {
name = propertyMap[attr.name];
} else {
name = attr.name;
}
// special cases for data attribute, we default to properties.attributes.data
if (name.indexOf('data-') === 0 || name.indexOf('aria-') === 0) {
value = attr.value;
isAttr = true;
} else {
value = attr.value;
}
return {
name: name
, value: value
, isAttr: isAttr || false
};
}
|
javascript
|
{
"resource": ""
}
|
q6535
|
createPropertyNS
|
train
|
function createPropertyNS(attr) {
var name, value;
return {
name: attr.name
, value: attr.value
, ns: namespaceMap[attr.name] || ''
};
}
|
javascript
|
{
"resource": ""
}
|
q6536
|
createStyleProperty
|
train
|
function createStyleProperty(el) {
var style = el.style;
var output = {};
for (var i = 0; i < style.length; ++i) {
var item = style.item(i);
output[item] = String(style[item]);
// hack to workaround browser inconsistency with url()
if (output[item].indexOf('url') > -1) {
output[item] = output[item].replace(/\"/g, '')
}
}
return { name: 'style', value: output };
}
|
javascript
|
{
"resource": ""
}
|
q6537
|
tagRepo
|
train
|
function tagRepo(version) {
if (SHOULD_PUBLISH) {
shell.exec(`git tag ${version}`);
shell.exec("git push origin --tags");
} else {
console.log(`\n\nWould publish git tag as version ${version}.`);
}
}
|
javascript
|
{
"resource": ""
}
|
q6538
|
ensureNoChangesOnMasterBeforePublish
|
train
|
function ensureNoChangesOnMasterBeforePublish() {
//Let users try the build script as long as they're not doing an actual publish
if (!SHOULD_PUBLISH) {
return true;
}
shell.exec("git fetch origin", {silent: true});
const currentBranch = shell.exec("git symbolic-ref --short -q HEAD", {silent: true});
if (currentBranch.stdout.trim() !== "master") {
shell.echo("Modules can only be deployed off 'master' branch.");
shell.exit(-1);
}
const changesOnBranch = shell.exec("git log HEAD..origin/master --oneline", {silent: true});
if (changesOnBranch.stdout.trim() !== "") {
shell.echo("Local repo and origin are out of sync! Have you pushed all your changes? Have you pulled the latest?");
shell.exit(-1);
}
const localChanges = shell.exec("git status --porcelain", {silent: true});
if (localChanges.stdout.trim() !== "") {
shell.echo("This git repository is has uncommitted files. Publish aborted!");
shell.exit(-1);
}
}
|
javascript
|
{
"resource": ""
}
|
q6539
|
Quote
|
train
|
function Quote(options) {
var self = this;
events.EventEmitter.call(self);
this.quote_id = options.quote_id;
this.start_time = new Date(parseInt(options.start_time,10)*1000);
this.end_time = new Date(parseInt(options.end_time,10)*1000);
this.fee = parseFloat(options.fee);
this.currency_code = options.currency_code;
if (options.pickup_eta) this.pickup_eta = parseInt(options.pickup_eta, 10);
if (options.dropoff_eta) this.dropoff_eta = parseInt(options.dropoff_eta, 10);
this.pickup_date = this.pickup_eta ? new Date(Date.now() + this.pickup_eta*60*1000) : null;
this.dropoff_date = this.dropoff_eta ? new Date(Date.now() + this.dropoff_eta*60*1000) : null;
}
|
javascript
|
{
"resource": ""
}
|
q6540
|
train
|
function(conversationId, userId, text, callback) {
send(null, conversationId, utils.messageText('user_id', userId, text), callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6541
|
train
|
function(conversationId, name, text, callback) {
send(null, conversationId, utils.messageText('name', name, text), callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6542
|
train
|
function(conversationId, params, callback) {
conversationId = utils.toUUID(conversationId);
if (!conversationId) return callback(new Error(utils.i18n.messages.cid));
utils.debug('Message getAll: ' + conversationId);
var queryParams = '';
if (typeof params === 'function') callback = params;
else queryParams = '?' + querystring.stringify(params);
request.get({
path: '/conversations/' + conversationId + '/messages' + queryParams
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6543
|
train
|
function(messageId, conversationId, callback) {
if (!messageId) return callback(new Error(utils.i18n.messages.mid));
messageId = utils.toUUID(messageId);
if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
conversationId = utils.toUUID(conversationId);
utils.debug('Message get: ' + messageId + ', ' + conversationId);
request.get({
path: '/conversations/' + conversationId + '/messages/' + messageId
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6544
|
train
|
function(userId, messageId, callback) {
if (!userId) return callback(new Error(utils.i18n.messages.userId));
messageId = utils.toUUID(messageId);
if (!messageId) return callback(new Error(utils.i18n.messages.mid));
utils.debug('Message getFromUser: ' + userId + ', ' + messageId);
request.get({
path: '/users/' + querystring.escape(userId) + '/messages/' + messageId
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6545
|
retryJob
|
train
|
function retryJob(job, when) {
when = when || 'later';
// Reaching maxRetries?
if (job.req.retries >= this.options.maxRetries)
return;
// Dropping from remains
delete this.remains[job.id];
// Request
job.req.retries++;
job.state.retrying = true;
// Adding to the queue again
this.queue[when === 'now' ? 'unshift' : 'push'](job);
this.emit('job:retry', job, when);
}
|
javascript
|
{
"resource": ""
}
|
q6546
|
beforeScraping
|
train
|
function beforeScraping(job, callback) {
return async.applyEachSeries(
this.middlewares.beforeScraping,
job.req,
callback
);
}
|
javascript
|
{
"resource": ""
}
|
q6547
|
afterScraping
|
train
|
function afterScraping(job, callback) {
return async.applyEachSeries(
this.middlewares.afterScraping,
job.req, job.res,
callback
);
}
|
javascript
|
{
"resource": ""
}
|
q6548
|
iterate
|
train
|
function iterate() {
var lastJob = this.lastJob || {},
feed = this.iterator.call(this, this.index, lastJob.req, lastJob.res);
if (feed)
this.addUrl(feed);
}
|
javascript
|
{
"resource": ""
}
|
q6549
|
addUrl
|
train
|
function addUrl(when, feed) {
if (!types.check(feed, 'feed') && !types.check(feed, ['feed']))
throw Error('sandcrawler.spider.url(s): wrong argument.');
var a = !(feed instanceof Array) ? [feed] : feed,
c = !this.state.running ? this.initialBuffer.length : this.index,
job,
i,
l;
for (i = 0, l = a.length; i < l; i++) {
job = createJob(a[i]);
// Don't add if already at limit
if (this.options.limit && c >= this.options.limit)
break;
if (!this.state.running) {
this.initialBuffer[when === 'later' ? 'push' : 'unshift'](job);
}
else {
this.queue[when === 'later' ? 'push' : 'unshift'](job);
this.emit('job:add', job);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q6550
|
train
|
function ( a, order, prop, prop2 )
{
var out = [];
var i=0, ien=order.length;
// Could have the test in the loop for slightly smaller code, but speed
// is essential here
if ( prop2 !== undefined ) {
for ( ; i<ien ; i++ ) {
out.push( a[ order[i] ][ prop ][ prop2 ] );
}
}
else {
for ( ; i<ien ; i++ ) {
out.push( a[ order[i] ][ prop ] );
}
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q6551
|
train
|
function ( src )
{
// A faster unique method is to use object keys to identify used values,
// but this doesn't work with arrays or objects, which we must also
// consider. See jsperf.com/compare-array-unique-versions/4 for more
// information.
var
out = [],
val,
i, ien=src.length,
j, k=0;
again: for ( i=0 ; i<ien ; i++ ) {
val = src[i];
for ( j=0 ; j<k ; j++ ) {
if ( out[j] === val ) {
continue again;
}
}
out.push( val );
k++;
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q6552
|
_fnHungarianMap
|
train
|
function _fnHungarianMap ( o )
{
var
hungarian = 'a aa ao as b fn i m o s ',
match,
newKey,
map = {};
$.each( o, function (key, val) {
match = key.match(/^([^A-Z]+?)([A-Z])/);
if ( match && hungarian.indexOf(match[1]+' ') !== -1 )
{
newKey = key.replace( match[0], match[2].toLowerCase() );
map[ newKey ] = key;
if ( match[1] === 'o' )
{
_fnHungarianMap( o[key] );
}
}
} );
o._hungarianMap = map;
}
|
javascript
|
{
"resource": ""
}
|
q6553
|
_fnCamelToHungarian
|
train
|
function _fnCamelToHungarian ( src, user, force )
{
if ( ! src._hungarianMap )
{
_fnHungarianMap( src );
}
var hungarianKey;
$.each( user, function (key, val) {
hungarianKey = src._hungarianMap[ key ];
if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) )
{
user[hungarianKey] = user[ key ];
if ( hungarianKey.charAt(0) === 'o' )
{
_fnCamelToHungarian( src[hungarianKey], user[key] );
}
}
} );
}
|
javascript
|
{
"resource": ""
}
|
q6554
|
_fnLanguageCompat
|
train
|
function _fnLanguageCompat( oLanguage )
{
var oDefaults = DataTable.defaults.oLanguage;
var zeroRecords = oLanguage.sZeroRecords;
/* Backwards compatibility - if there is no sEmptyTable given, then use the same as
* sZeroRecords - assuming that is given.
*/
if ( !oLanguage.sEmptyTable && zeroRecords &&
oDefaults.sEmptyTable === "No data available in table" )
{
_fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sEmptyTable' );
}
/* Likewise with loading records */
if ( !oLanguage.sLoadingRecords && zeroRecords &&
oDefaults.sLoadingRecords === "Loading..." )
{
_fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sLoadingRecords' );
}
}
|
javascript
|
{
"resource": ""
}
|
q6555
|
train
|
function ( o, knew, old ) {
if ( o[ knew ] !== undefined ) {
o[ old ] = o[ knew ];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6556
|
_fnCompatOpts
|
train
|
function _fnCompatOpts ( init )
{
_fnCompatMap( init, 'ordering', 'bSort' );
_fnCompatMap( init, 'orderMulti', 'bSortMulti' );
_fnCompatMap( init, 'orderClasses', 'bSortClasses' );
_fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' );
_fnCompatMap( init, 'order', 'aaSorting' );
_fnCompatMap( init, 'orderFixed', 'aaSortingFixed' );
_fnCompatMap( init, 'paging', 'bPaginate' );
_fnCompatMap( init, 'pagingType', 'sPaginationType' );
_fnCompatMap( init, 'pageLength', 'iDisplayLength' );
_fnCompatMap( init, 'searching', 'bFilter' );
}
|
javascript
|
{
"resource": ""
}
|
q6557
|
_fnCompatCols
|
train
|
function _fnCompatCols ( init )
{
_fnCompatMap( init, 'orderable', 'bSortable' );
_fnCompatMap( init, 'orderData', 'aDataSort' );
_fnCompatMap( init, 'orderSequence', 'asSorting' );
_fnCompatMap( init, 'orderDataType', 'sortDataType' );
}
|
javascript
|
{
"resource": ""
}
|
q6558
|
_fnBrowserDetect
|
train
|
function _fnBrowserDetect( settings )
{
var browser = settings.oBrowser;
// Scrolling feature / quirks detection
var n = $('<div/>')
.css( {
position: 'absolute',
top: 0,
left: 0,
height: 1,
width: 1,
overflow: 'hidden'
} )
.append(
$('<div/>')
.css( {
position: 'absolute',
top: 1,
left: 1,
width: 100,
overflow: 'scroll'
} )
.append(
$('<div class="test"/>')
.css( {
width: '100%',
height: 10
} )
)
)
.appendTo( 'body' );
var test = n.find('.test');
// IE6/7 will oversize a width 100% element inside a scrolling element, to
// include the width of the scrollbar, while other browsers ensure the inner
// element is contained without forcing scrolling
browser.bScrollOversize = test[0].offsetWidth === 100;
// In rtl text layout, some browsers (most, but not all) will place the
// scrollbar on the left, rather than the right.
browser.bScrollbarLeft = test.offset().left !== 1;
n.remove();
}
|
javascript
|
{
"resource": ""
}
|
q6559
|
_fnGetColumns
|
train
|
function _fnGetColumns( oSettings, sParam )
{
var a = [];
$.map( oSettings.aoColumns, function(val, i) {
if ( val[sParam] ) {
a.push( i );
}
} );
return a;
}
|
javascript
|
{
"resource": ""
}
|
q6560
|
_fnApplyColumnDefs
|
train
|
function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
{
var i, iLen, j, jLen, k, kLen, def;
// Column definitions with aTargets
if ( aoColDefs )
{
/* Loop over the definitions array - loop in reverse so first instance has priority */
for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
{
def = aoColDefs[i];
/* Each definition can target multiple columns, as it is an array */
var aTargets = def.targets !== undefined ?
def.targets :
def.aTargets;
if ( ! $.isArray( aTargets ) )
{
aTargets = [ aTargets ];
}
for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
{
if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
{
/* Add columns that we don't yet know about */
while( oSettings.aoColumns.length <= aTargets[j] )
{
_fnAddColumn( oSettings );
}
/* Integer, basic index */
fn( aTargets[j], def );
}
else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
{
/* Negative integer, right to left column counting */
fn( oSettings.aoColumns.length+aTargets[j], def );
}
else if ( typeof aTargets[j] === 'string' )
{
/* Class name matching on TH element */
for ( k=0, kLen=oSettings.aoColumns.length ; k<kLen ; k++ )
{
if ( aTargets[j] == "_all" ||
$(oSettings.aoColumns[k].nTh).hasClass( aTargets[j] ) )
{
fn( k, def );
}
}
}
}
}
}
// Statically defined columns array
if ( aoCols )
{
for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
{
fn( i, aoCols[i] );
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6561
|
_fnGetCellData
|
train
|
function _fnGetCellData( oSettings, iRow, iCol, sSpecific )
{
var oCol = oSettings.aoColumns[iCol];
var oData = oSettings.aoData[iRow]._aData;
var sData = oCol.fnGetData( oData, sSpecific );
if ( sData === undefined )
{
if ( oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null )
{
_fnLog( oSettings, 0, "Requested unknown parameter "+
(typeof oCol.mData=='function' ? '{function}' : "'"+oCol.mData+"'")+
" for row "+iRow, 4 );
oSettings.iDrawError = oSettings.iDraw;
}
return oCol.sDefaultContent;
}
/* When the data source is null, we can use default column data */
if ( (sData === oData || sData === null) && oCol.sDefaultContent !== null )
{
sData = oCol.sDefaultContent;
}
else if ( typeof sData === 'function' )
{
// If the data source is a function, then we run it and use the return
return sData();
}
if ( sData === null && sSpecific == 'display' )
{
return '';
}
return sData;
}
|
javascript
|
{
"resource": ""
}
|
q6562
|
_fnInvalidateRow
|
train
|
function _fnInvalidateRow( settings, rowIdx, src, column )
{
var row = settings.aoData[ rowIdx ];
var i, ien;
// Are we reading last data from DOM or the data object?
if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {
// Read the data from the DOM
row._aData = _fnGetRowElements( settings, row.nTr ).data;
}
else {
// Reading from data object, update the DOM
var cells = row.anCells;
for ( i=0, ien=cells.length ; i<ien ; i++ ) {
cells[i].innerHTML = _fnGetCellData( settings, rowIdx, i, 'display' );
}
}
row._aSortData = null;
row._aFilterData = null;
// Invalidate the type for a specific column (if given) or all columns since
// the data might have changed
var cols = settings.aoColumns;
if ( column !== undefined ) {
cols[ column ].sType = null;
}
else {
for ( i=0, ien=cols.length ; i<ien ; i++ ) {
cols[i].sType = null;
}
}
// Update DataTables special `DT_*` attributes for the row
_fnRowAttributes( row );
}
|
javascript
|
{
"resource": ""
}
|
q6563
|
_fnGetRowElements
|
train
|
function _fnGetRowElements( settings, row )
{
var
d = [],
tds = [],
td = row.firstChild,
name, col, o, i=0, contents,
columns = settings.aoColumns;
var attr = function ( str, data, td ) {
if ( typeof str === 'string' ) {
var idx = str.indexOf('@');
if ( idx !== -1 ) {
var src = str.substring( idx+1 );
o[ '@'+src ] = td.getAttribute( src );
}
}
};
while ( td ) {
name = td.nodeName.toUpperCase();
if ( name == "TD" || name == "TH" ) {
col = columns[i];
contents = $.trim(td.innerHTML);
if ( col && col._bAttrSrc ) {
o = {
display: contents
};
attr( col.mData.sort, o, td );
attr( col.mData.type, o, td );
attr( col.mData.filter, o, td );
d.push( o );
}
else {
d.push( contents );
}
tds.push( td );
i++;
}
td = td.nextSibling;
}
return {
data: d,
cells: tds
};
}
|
javascript
|
{
"resource": ""
}
|
q6564
|
_fnBuildAjax
|
train
|
function _fnBuildAjax( oSettings, data, fn )
{
// Compatibility with 1.9-, allow fnServerData and event to manipulate
_fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] );
// Convert to object based for 1.10+ if using the old scheme
if ( data && data.__legacy ) {
var tmp = {};
var rbracket = /(.*?)\[\]$/;
$.each( data, function (key, val) {
var match = val.name.match(rbracket);
if ( match ) {
// Support for arrays
var name = match[0];
if ( ! tmp[ name ] ) {
tmp[ name ] = [];
}
tmp[ name ].push( val.value );
}
else {
tmp[val.name] = val.value;
}
} );
data = tmp;
}
var ajaxData;
var ajax = oSettings.ajax;
var instance = oSettings.oInstance;
if ( $.isPlainObject( ajax ) && ajax.data )
{
ajaxData = ajax.data;
var newData = $.isFunction( ajaxData ) ?
ajaxData( data ) : // fn can manipulate data or return an object
ajaxData; // object or array to merge
// If the function returned an object, use that alone
data = $.isFunction( ajaxData ) && newData ?
newData :
$.extend( true, data, newData );
// Remove the data property as we've resolved it already and don't want
// jQuery to do it again (it is restored at the end of the function)
delete ajax.data;
}
var baseAjax = {
"data": data,
"success": function (json) {
var error = json.error || json.sError;
if ( error ) {
oSettings.oApi._fnLog( oSettings, 0, error );
}
oSettings.json = json;
_fnCallbackFire( oSettings, null, 'xhr', [oSettings, json] );
fn( json );
},
"dataType": "json",
"cache": false,
"type": oSettings.sServerMethod,
"error": function (xhr, error, thrown) {
var log = oSettings.oApi._fnLog;
if ( error == "parsererror" ) {
log( oSettings, 0, 'Invalid JSON response', 1 );
}
else {
log( oSettings, 0, 'Ajax error', 7 );
}
}
};
if ( oSettings.fnServerData )
{
// DataTables 1.9- compatibility
oSettings.fnServerData.call( instance,
oSettings.sAjaxSource, data, fn, oSettings
);
}
else if ( oSettings.sAjaxSource || typeof ajax === 'string' )
{
// DataTables 1.9- compatibility
oSettings.jqXHR = $.ajax( $.extend( baseAjax, {
url: ajax || oSettings.sAjaxSource
} ) );
}
else if ( $.isFunction( ajax ) )
{
// Is a function - let the caller define what needs to be done
oSettings.jqXHR = ajax.call( instance, data, fn, oSettings );
}
else
{
// Object to extend the base settings
oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) );
// Restore for next time around
ajax.data = ajaxData;
}
}
|
javascript
|
{
"resource": ""
}
|
q6565
|
_fnAjaxDataSrc
|
train
|
function _fnAjaxDataSrc ( oSettings, json )
{
var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ?
oSettings.ajax.dataSrc :
oSettings.sAjaxDataProp; // Compatibility with 1.9-.
// Compatibility with 1.9-. In order to read from aaData, check if the
// default has been changed, if not, check for aaData
if ( dataSrc === 'data' ) {
return json.aaData || json[dataSrc];
}
return dataSrc !== "" ?
_fnGetObjectDataFn( dataSrc )( json ) :
json;
}
|
javascript
|
{
"resource": ""
}
|
q6566
|
train
|
function(nSizer) {
var style = nSizer.style;
style.paddingTop = "0";
style.paddingBottom = "0";
style.borderTopWidth = "0";
style.borderBottomWidth = "0";
style.height = 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q6567
|
_fnScrollingWidthAdjust
|
train
|
function _fnScrollingWidthAdjust ( settings, n )
{
var scroll = settings.oScroll;
if ( scroll.sX || scroll.sY ) {
// When y-scrolling only, we want to remove the width of the scroll bar
// so the table + scroll bar will fit into the area available, otherwise
// we fix the table at its current size with no adjustment
var correction = ! scroll.sX ? scroll.iBarWidth : 0;
n.style.width = _fnStringToCss( $(n).outerWidth() - correction );
}
}
|
javascript
|
{
"resource": ""
}
|
q6568
|
_fnScrollBarWidth
|
train
|
function _fnScrollBarWidth ()
{
// On first run a static variable is set, since this is only needed once.
// Subsequent runs will just use the previously calculated value
if ( ! DataTable.__scrollbarWidth ) {
var inner = $('<p/>').css( {
width: '100%',
height: 200,
padding: 0
} )[0];
var outer = $('<div/>')
.css( {
position: 'absolute',
top: 0,
left: 0,
width: 200,
height: 150,
padding: 0,
overflow: 'hidden',
visibility: 'hidden'
} )
.append( inner )
.appendTo( 'body' );
var w1 = inner.offsetWidth;
outer.css( 'overflow', 'scroll' );
var w2 = inner.offsetWidth;
if ( w1 === w2 ) {
w2 = outer[0].clientWidth;
}
outer.remove();
DataTable.__scrollbarWidth = w1 - w2;
}
return DataTable.__scrollbarWidth;
}
|
javascript
|
{
"resource": ""
}
|
q6569
|
_fnSortListener
|
train
|
function _fnSortListener ( settings, colIdx, append, callback )
{
var col = settings.aoColumns[ colIdx ];
var sorting = settings.aaSorting;
var asSorting = col.asSorting;
var nextSortIdx;
var next = function ( a ) {
var idx = a._idx;
if ( idx === undefined ) {
idx = $.inArray( a[1], asSorting );
}
return idx+1 >= asSorting.length ? 0 : idx+1;
};
// If appending the sort then we are multi-column sorting
if ( append && settings.oFeatures.bSortMulti ) {
// Are we already doing some kind of sort on this column?
var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') );
if ( sortIdx !== -1 ) {
// Yes, modify the sort
nextSortIdx = next( sorting[sortIdx] );
sorting[sortIdx][1] = asSorting[ nextSortIdx ];
sorting[sortIdx]._idx = nextSortIdx;
}
else {
// No sort on this column yet
sorting.push( [ colIdx, asSorting[0], 0 ] );
sorting[sorting.length-1]._idx = 0;
}
}
else if ( sorting.length && sorting[0][0] == colIdx ) {
// Single column - already sorting on this column, modify the sort
nextSortIdx = next( sorting[0] );
sorting.length = 1;
sorting[0][1] = asSorting[ nextSortIdx ];
sorting[0]._idx = nextSortIdx;
}
else {
// Single column - sort only on this column
sorting.length = 0;
sorting.push( [ colIdx, asSorting[0] ] );
sorting[0]._idx = 0;
}
// Run the sort by calling a full redraw
_fnReDraw( settings );
// callback used for async user interaction
if ( typeof callback == 'function' ) {
callback( settings );
}
}
|
javascript
|
{
"resource": ""
}
|
q6570
|
_fnLoadState
|
train
|
function _fnLoadState ( oSettings, oInit )
{
var i, ien;
var columns = oSettings.aoColumns;
if ( !oSettings.oFeatures.bStateSave )
{
return;
}
var oData = oSettings.fnStateLoadCallback.call( oSettings.oInstance, oSettings );
if ( !oData )
{
return;
}
/* Allow custom and plug-in manipulation functions to alter the saved data set and
* cancelling of loading by returning false
*/
var abStateLoad = _fnCallbackFire( oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData] );
if ( $.inArray( false, abStateLoad ) !== -1 )
{
return;
}
/* Reject old data */
if ( oData.iCreate < new Date().getTime() - (oSettings.iStateDuration*1000) ) {
return;
}
// Number of columns have changed - all bets are off, no restore of settings
if ( columns.length !== oData.aoSearchCols.length ) {
return;
}
/* Store the saved state so it might be accessed at any time */
oSettings.oLoadedState = $.extend( true, {}, oData );
/* Restore key features */
oSettings._iDisplayStart = oData.iStart;
oSettings.iInitDisplayStart = oData.iStart;
oSettings._iDisplayLength = oData.iLength;
oSettings.aaSorting = [];
var savedSort = oData.aaSorting;
for ( i=0, ien=savedSort.length ; i<ien ; i++ ) {
oSettings.aaSorting.push( savedSort[i][0] >= columns.length ?
[ 0, savedSort[i][1] ] :
savedSort[i]
);
}
/* Search filtering */
$.extend( oSettings.oPreviousSearch, oData.oSearch );
$.extend( true, oSettings.aoPreSearchCols, oData.aoSearchCols );
/* Column visibility state */
for ( i=0, ien=oData.abVisCols.length ; i<ien ; i++ ) {
columns[i].bVisible = oData.abVisCols[i];
}
_fnCallbackFire( oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData] );
}
|
javascript
|
{
"resource": ""
}
|
q6571
|
train
|
function ( mixed )
{
var idx, jq;
var settings = DataTable.settings;
var tables = $.map( settings, function (el, i) {
return el.nTable;
} );
if ( mixed.nTable && mixed.oApi ) {
// DataTables settings object
return [ mixed ];
}
else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) {
// Table node
idx = $.inArray( mixed, tables );
return idx !== -1 ? [ settings[idx] ] : null;
}
else if ( typeof mixed === 'string' ) {
// jQuery selector
jq = $(mixed);
}
else if ( mixed instanceof $ ) {
// jQuery object (also DataTables instance)
jq = mixed;
}
if ( jq ) {
return jq.map( function(i) {
idx = $.inArray( this, tables );
return idx !== -1 ? settings[idx] : null;
} );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6572
|
train
|
function ( fn )
{
if ( __arrayProto.forEach ) {
// Where possible, use the built-in forEach
__arrayProto.forEach.call( this, fn, this );
}
else {
// Compatibility for browsers without EMCA-252-5 (JS 1.6)
for ( var i=0, ien=this.length ; i<ien; i++ ) {
// In strict mode the execution scope is the passed value
fn.call( this, this[i], i, this );
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6573
|
train
|
function ( flatten, type, fn ) {
var
a = [], ret,
i, ien, j, jen,
context = this.context,
rows, items, item,
selector = this.selector;
// Argument shifting
if ( typeof flatten === 'string' ) {
fn = type;
type = flatten;
flatten = false;
}
for ( i=0, ien=context.length ; i<ien ; i++ ) {
if ( type === 'table' ) {
ret = fn( context[i], i );
if ( ret !== undefined ) {
a.push( ret );
}
}
else if ( type === 'columns' || type === 'rows' ) {
// this has same length as context - one entry for each table
ret = fn( context[i], this[i], i );
if ( ret !== undefined ) {
a.push( ret );
}
}
else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) {
// columns and rows share the same structure.
// 'this' is an array of column indexes for each context
items = this[i];
if ( type === 'column-rows' ) {
rows = _selector_row_indexes( context[i], selector.opts );
}
for ( j=0, jen=items.length ; j<jen ; j++ ) {
item = items[j];
if ( type === 'cell' ) {
ret = fn( context[i], item.row, item.column, i, j );
}
else {
ret = fn( context[i], item, i, j, rows );
}
if ( ret !== undefined ) {
a.push( ret );
}
}
}
}
if ( a.length ) {
var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a );
var apiSelector = api.selector;
apiSelector.rows = selector.rows;
apiSelector.cols = selector.cols;
apiSelector.opts = selector.opts;
return api;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6574
|
train
|
function ( selector, a )
{
// Integer is used to pick out a table by index
if ( typeof selector === 'number' ) {
return [ a[ selector ] ];
}
// Perform a jQuery selector on the table nodes
var nodes = $.map( a, function (el, i) {
return el.nTable;
} );
return $(nodes)
.filter( selector )
.map( function (i) {
// Need to translate back from the table node to the settings
var idx = $.inArray( this, nodes );
return a[ idx ];
} )
.toArray();
}
|
javascript
|
{
"resource": ""
}
|
|
q6575
|
train
|
function ()
{
var
len = this._iDisplayLength,
start = this._iDisplayStart,
calc = start + len,
records = this.aiDisplay.length,
features = this.oFeatures,
paginate = features.bPaginate;
if ( features.bServerSide ) {
return paginate === false || len === -1 ?
start + records :
Math.min( start+len, this._iRecordsDisplay );
}
else {
return ! paginate || calc>records || len===-1 ?
records :
calc;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6576
|
train
|
function(userId, callback) {
if (!userId) return callback(new Error(utils.i18n.identities.id));
utils.debug('Identities get: ' + userId);
request.get({
path: '/users/' + userId + '/identity'
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6577
|
train
|
function(userId, properties, callback) {
if (!userId) return callback(new Error(utils.i18n.identities.id));
utils.debug('Identity edit: ' + userId);
request.patch({
path: '/users/' + userId + '/identity',
body: Object.keys(properties).map(function(propertyName) {
return {
operation: 'set',
property: propertyName,
value: properties[propertyName]
};
})
}, callback || utils.nop);
}
|
javascript
|
{
"resource": ""
}
|
|
q6578
|
train
|
function(website) {
var self = this;
var scriptPath = path.dirname(website.script);
var script = '';
var port = website.port;
if(website.absoluteScript === false) {
scriptPath = process.cwd() + '/' + path.dirname(website.script);
}
script = path.basename(website.script);
var env = JSON.parse(JSON.stringify(process.env));
env.PORT = port;
var spawnOptions = {
env: env,
cwd: scriptPath,
stdio: 'pipe',
detached: false
};
var child = childProcess.spawn(process.execPath, [script], spawnOptions);
website.process = child;
website.processStatus = 'start';
child.stderr.on('data', function(chunk) {
website.writeLog(chunk.toString('utf8'), 'error');
});
child.stdout.on('data', function(chunk) {
website.writeLog(chunk.toString('utf8'), 'log');
});
child.on('exit', function(code, signal) {
website.writeLog('cgi spawn ' + child.pid + ' "exit" event (code ' + code + ') (signal ' + signal + ') (status ' + website.processStatus + ')', 'log');
if(website.processStatus == 'stop') {
website.processStatus = 'end';
} else {
website.processStatus = 'end';
self.start(website);
}
});
website.operations = {
stop: function() {
website.processStatus = 'stop';
child.kill('SIGINT');
},
reboot: function() {
website.processStatus = 'stop';
child.kill('SIGINT');
website.operations.stop();
website.operations.start();
},
start: function() {
self.start(website);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q6579
|
commaNumber
|
train
|
function commaNumber(inputNumber, optionalSeparator, optionalDecimalChar) {
// we'll strip off and hold the decimal value to reattach later.
// we'll hold both the `number` value and `stringNumber` value.
let number, stringNumber, decimal
// default `separator` is a comma
const separator = optionalSeparator || ','
// default `decimalChar` is a period
const decimalChar = optionalDecimalChar || '.'
switch (typeof inputNumber) {
case 'string':
// if there aren't enough digits to need separators then return it
// NOTE: some numbers which are too small will get passed this
// when they have decimal values which make them too long here.
// but, the number value check after this switch will catch it.
if (inputNumber.length < (inputNumber[0] === '-' ? 5 : 4)) {
return inputNumber
}
// remember it as a string in `stringNumber` and convert to a Number
stringNumber = inputNumber
// if they're not using the Node standard decimal char then replace it
// before converting.
number = decimalChar !== '.' ? Number(stringNumber.replace(decimalChar, '.'))
: Number(stringNumber)
break
// convert to a string.
// NOTE: don't check if the number is too small before converting
// because we'll need to return `stringNumber` anyway.
case 'number':
stringNumber = String(inputNumber)
number = inputNumber
break
// return invalid type as-is
default: return inputNumber
}
// when it doesn't need a separator or isn't a number then return it
if ((-1000 < number && number < 1000) || isNaN(number) || !isFinite(number)) {
return stringNumber
}
// strip off decimal value to append to the final result at the bottom
let decimalIndex = stringNumber.lastIndexOf(decimalChar)
if (decimalIndex > -1) {
decimal = stringNumber.slice(decimalIndex)
stringNumber = stringNumber.slice(0, -decimal.length)
}
// else {
// decimal = null
// }
// finally, parse the string and add in separators
stringNumber = parse(stringNumber, separator)
// if there's a decimal value add it back on the end.
// NOTE: we sliced() it off including the decimalChar, so it's good.
return decimal ? stringNumber + decimal : stringNumber
}
|
javascript
|
{
"resource": ""
}
|
q6580
|
train
|
function () {
var coming = F.coming;
if (!coming || false === F.trigger('onCancel')) {
return;
}
F.hideLoading();
if (F.ajaxLoad) {
F.ajaxLoad.abort();
}
F.ajaxLoad = null;
if (F.imgPreload) {
F.imgPreload.onload = F.imgPreload.onerror = null;
}
if (coming.wrap) {
coming.wrap.stop(true, true).trigger('onReset').remove();
}
F.coming = null;
// If the first item has been canceled, then clear everything
if (!F.current) {
F._afterZoomOut( coming );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6581
|
train
|
function ( direction ) {
var current = F.current;
if (current) {
if (!isString(direction)) {
direction = current.direction.next;
}
F.jumpto(current.index + 1, direction, 'next');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6582
|
train
|
function ( direction ) {
var current = F.current;
if (current) {
if (!isString(direction)) {
direction = current.direction.prev;
}
F.jumpto(current.index - 1, direction, 'prev');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6583
|
train
|
function ( index, direction, router ) {
var current = F.current;
if (!current) {
return;
}
index = getScalar(index);
F.direction = direction || current.direction[ (index >= current.index ? 'next' : 'prev') ];
F.router = router || 'jumpto';
if (current.loop) {
if (index < 0) {
index = current.group.length + (index % current.group.length);
}
index = index % current.group.length;
}
if (current.group[ index ] !== undefined) {
F.cancel();
F._start(index);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6584
|
train
|
function (e, onlyAbsolute) {
var current = F.current,
wrap = current ? current.wrap : null,
pos;
if (wrap) {
pos = F._getPosition(onlyAbsolute);
if (e && e.type === 'scroll') {
delete pos.position;
wrap.stop(true, true).animate(pos, 200);
} else {
wrap.css(pos);
current.pos = $.extend({}, current.dim, pos);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6585
|
train
|
function ( action ) {
if (F.isOpen) {
F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView;
// Help browser to restore document dimensions
if (isTouch) {
F.wrap.removeAttr('style').addClass('fancybox-tmp');
F.trigger('onUpdate');
}
F.update();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6586
|
train
|
function(opts) {
opts = $.extend({}, this.defaults, opts);
if (this.overlay) {
this.close();
}
this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( F.coming ? F.coming.parent : opts.parent );
this.fixed = false;
if (opts.fixed && F.defaults.fixed) {
this.overlay.addClass('fancybox-overlay-fixed');
this.fixed = true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6587
|
train
|
function (opts, obj) {
var overlay = this.overlay;
$('.fancybox-overlay').stop(true, true);
if (!overlay) {
this.create(opts);
}
if (opts.locked && this.fixed && obj.fixed) {
if (!overlay) {
this.margin = D.height() > W.height() ? $('html').css('margin-right').replace("px", "") : false;
}
obj.locked = this.overlay.append( obj.wrap );
obj.fixed = false;
}
if (opts.showEarly === true) {
this.beforeShow.apply(this, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6588
|
train
|
function(conversationId, callback) {
conversationId = utils.toUUID(conversationId);
if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
utils.debug('Conversation get: ' + conversationId);
request.get({
path: '/conversations/' + conversationId
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6589
|
train
|
function(userId, conversationId, callback) {
if (!userId) return callback(new Error(utils.i18n.conversations.userId));
conversationId = utils.toUUID(conversationId);
if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
utils.debug('Conversation getFromUser: ' + userId + ', ' + conversationId);
request.get({
path: '/users/' + querystring.escape(userId) + '/conversations/' + conversationId
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6590
|
train
|
function(userId, params, callback) {
if (!userId) return callback(new Error(utils.i18n.conversations.userId));
utils.debug('Conversation getAllFromUser: ' + userId);
var queryParams = '';
if (typeof params === 'function') callback = params;
else queryParams = '?' + querystring.stringify(params);
request.get({
path: '/users/' + querystring.escape(userId) + '/conversations' + queryParams
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6591
|
train
|
function(conversationId, operations, callback) {
conversationId = utils.toUUID(conversationId);
if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
if (!utils.isArray(operations)) return callback(new Error(utils.i18n.conversations.operations));
utils.debug('Conversation edit: ' + conversationId);
edit(conversationId, operations, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6592
|
train
|
function(conversationId, properties, callback) {
conversationId = utils.toUUID(conversationId);
if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
utils.debug('Conversation setMetadataProperties: ' + conversationId);
var operations = [];
Object.keys(properties).forEach(function(name) {
var fullName = name;
if (name !== 'metadata' && name.indexOf('metadata.') !== 0) {
fullName = 'metadata.' + name;
}
operations.push({
operation: 'set',
property: fullName,
value: String(properties[name]),
});
});
edit(conversationId, operations, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6593
|
train
|
function(conversationId, properties, callback) {
conversationId = utils.toUUID(conversationId);
if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
utils.debug('Conversation deleteMetadataProperties: ' + conversationId);
var operations = [];
Object.keys(properties).forEach(function(property) {
if (property !== 'metadata' && property.indexOf('metadata.') !== 0) {
property = 'metadata.' + property;
}
operations.push({
operation: 'delete',
property: property,
});
});
edit(conversationId, operations, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6594
|
resolveArgument
|
train
|
function resolveArgument(expr, argIndex) {
if (typeof argIndex === 'undefined') {
argIndex = 0;
}
if (!expr.arguments.length || !expr.arguments[argIndex]) {
return;
}
this.applyPluginsBailResult('call require:commonjs:item', expr,
this.evaluateExpression(expr.arguments[argIndex]));
}
|
javascript
|
{
"resource": ""
}
|
q6595
|
getEntryPoints
|
train
|
function getEntryPoints(globPattern) {
var testFiles = glob.sync(globPattern);
var entryPoints = {};
testFiles.forEach(function(file) {
entryPoints[file.replace(/\.js$/, '')] = './' + file;
});
return entryPoints;
}
|
javascript
|
{
"resource": ""
}
|
q6596
|
polymerBuild
|
train
|
function polymerBuild(config) {
const skipRootFolder = function(file) {
const rootFolder = config.root || '.';
file.dirname = path.relative(rootFolder, file.dirname);
};
const project = new build.PolymerProject(config);
const bundler = project.bundler({
// XXX: sourcemaps makes V8 run out of memory
sourcemaps: false,
stripComments: true,
}).on('error', e => console.error(e));
return merge(project.sources(), project.dependencies())
.pipe(bundler)
.pipe(size({title: 'polymer-bundler'}))
.pipe(rename(skipRootFolder));
}
|
javascript
|
{
"resource": ""
}
|
q6597
|
serializeError
|
train
|
function serializeError(err) {
var o = {};
Object.getOwnPropertyNames(err).forEach(function (k) {
o[k] = err[k];
});
return _.omit(o, ['stack', 'type', 'arguments']);
}
|
javascript
|
{
"resource": ""
}
|
q6598
|
serializeCookie
|
train
|
function serializeCookie(cookie) {
return {
path: cookie.path,
name: cookie.key,
value: cookie.value,
domain: cookie.domain
};
}
|
javascript
|
{
"resource": ""
}
|
q6599
|
norm16
|
train
|
function norm16(v) {
v = parseInt(v, 16);
return size == 2 ? v : // 16 bit
size == 1 ? v << 4 : // 8 bit
v >> (4 * (size - 2)); // 24 or 32 bit
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.