_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q65100 | node | test | function node(content, type, name, indent){
this.type = type;
if(name) this.name = name;
this.content = content;
if(indent) {
this.indent = indent;// to use same indentation as source code
if(~eol.indexOf(indent[0])){
delete this.indent;
}
}
var loc = location();
var bol = loc.start.column == 1;
if(bol) this.bol = true;
this.line = loc.start.line;
this.column = loc.start.column;
} | javascript | {
"resource": ""
} |
q65101 | f | test | function f(arr) {
if(arr){
var merged = [];
return merged.concat.apply(merged, arr).join("")
}
} | javascript | {
"resource": ""
} |
q65102 | configureStore | test | function configureStore(onComplete) {
// Apply middlewares
var middlewares = [thunk];
events.emit('middlewaresWillApply', middlewares);
if (__DEV__ && !!window.navigator.userAgent) {
middlewares.push(createLogger({
collapsed: true,
duration: true,
}));
}
// Create store
var storeCreator = applyMiddleware.apply(null, middlewares)(createStore);
var result = {}; // {store: <created store>}
events.emit('storeWillCreate', storeCreator, reducers, onComplete, result);
if (result.store === undefined) {
result.store = storeCreator(reducers);
setTimeout(onComplete, 0);
}
global.reduxStore = result.store;
return reduxStore;
} | javascript | {
"resource": ""
} |
q65103 | test | function(el, config) {
var me = this;
config = config || {};
Ext.apply(me, config);
/**
* @event dropactivate
* @param {Ext.util.Droppable} this
* @param {Ext.util.Draggable} draggable
* @param {Ext.event.Event} e
*/
/**
* @event dropdeactivate
* @param {Ext.util.Droppable} this
* @param {Ext.util.Draggable} draggable
* @param {Ext.event.Event} e
*/
/**
* @event dropenter
* @param {Ext.util.Droppable} this
* @param {Ext.util.Draggable} draggable
* @param {Ext.event.Event} e
*/
/**
* @event dropleave
* @param {Ext.util.Droppable} this
* @param {Ext.util.Draggable} draggable
* @param {Ext.event.Event} e
*/
/**
* @event drop
* @param {Ext.util.Droppable} this
* @param {Ext.util.Draggable} draggable
* @param {Ext.event.Event} e
*/
me.el = Ext.get(el);
me.callParent();
me.mixins.observable.constructor.call(me);
if (!me.disabled) {
me.enable();
}
me.el.addCls(me.baseCls);
} | javascript | {
"resource": ""
} |
|
q65104 | test | function() {
if (!this.mgr) {
this.mgr = Ext.util.Observable.observe(Ext.util.Draggable);
}
this.mgr.on({
dragstart: this.onDragStart,
scope: this
});
this.disabled = false;
} | javascript | {
"resource": ""
} |
|
q65105 | rel | test | function rel(root, src, sep) {
if(!root || !_.isString(root) || !src || !_.isString(src)) return
let root_split = root.split(path.sep),
src_split = src.split(path.sep)
return _.join(_.difference(src_split, root_split), sep || '/')
} | javascript | {
"resource": ""
} |
q65106 | rebase | test | function rebase(root, src, dest) {
let relp = rel(root, src)
return relp ? path.join(dest, relp) : ''
} | javascript | {
"resource": ""
} |
q65107 | lookupLevel | test | function lookupLevel(level) {
if (typeof level === 'string') {
var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
if (levelMap >= 0) {
level = levelMap;
} else {
level = parseInt(level, 10);
}
}
return level;
} | javascript | {
"resource": ""
} |
q65108 | log | test | function log(level) {
level = logger.lookupLevel(level);
if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
var method = logger.methodMap[level];
if (!console[method]) {
// eslint-disable-line no-console
method = 'log';
}
for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
message[_key - 1] = arguments[_key];
}
console[method].apply(console, message); // eslint-disable-line no-console
}
} | javascript | {
"resource": ""
} |
q65109 | simpleId | test | function simpleId(path) {
return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
} | javascript | {
"resource": ""
} |
q65110 | acceptKey | test | function acceptKey(node, name) {
var value = this.accept(node[name]);
if (this.mutating) {
// Hacky sanity check: This may have a few false positives for type for the helper
// methods but will generally do the right thing without a lot of overhead.
if (value && !Visitor.prototype[value.type]) {
throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
}
node[name] = value;
}
} | javascript | {
"resource": ""
} |
q65111 | acceptRequired | test | function acceptRequired(node, name) {
this.acceptKey(node, name);
if (!node[name]) {
throw new _exception2['default'](node.type + ' requires ' + name);
}
} | javascript | {
"resource": ""
} |
q65112 | acceptArray | test | function acceptArray(array) {
for (var i = 0, l = array.length; i < l; i++) {
this.acceptKey(array, i);
if (!array[i]) {
array.splice(i, 1);
i--;
l--;
}
}
} | javascript | {
"resource": ""
} |
q65113 | ret | test | function ret(context, execOptions) {
if (!compiled) {
compiled = compileInput();
}
return compiled.call(this, context, execOptions);
} | javascript | {
"resource": ""
} |
q65114 | reduceChildListMutation | test | function reduceChildListMutation(mutationContent, record) {
const isAdded = Boolean(record.addedNodes.length);
const isNext = Boolean(record.nextSibling);
const isPrev = Boolean(record.previousSibling);
const isRemoved = Boolean(record.removedNodes.length);
// innerHTML or replace
if (isAdded && (isRemoved || (!isRemoved && !isNext && !isPrev))) {
while (mutationContent.firstChild) {
mutationContent.removeChild(mutationContent.firstChild);
}
forEach(record.addedNodes, function (node) {
mutationContent.appendChild(node);
});
// appendChild
} else if (isAdded && !isRemoved && !isNext && isPrev) {
forEach(record.addedNodes, function (node) {
mutationContent.appendChild(node);
});
// insertBefore
} else if (isAdded && !isRemoved && isNext && !isPrev) {
forEach(record.addedNodes, function (node) {
mutationContent.insertBefore(node, mutationContent.firstChild);
});
}
return mutationContent;
} | javascript | {
"resource": ""
} |
q65115 | Node | test | function Node (options) {
if (!(this instanceof Node)) {
return new Node(options)
}
events.EventEmitter.call(this)
this._setStorageAdapter(options.storage)
this._log = options.logger
this._rpc = options.transport
this._self = this._rpc._contact
this._validator = options.validator
this._router = options.router || new Router({
logger: this._log,
transport: this._rpc,
validator: this._validateKeyValuePair.bind(this)
})
this._bindRouterEventHandlers()
this._bindRPCMessageHandlers()
this._startReplicationInterval()
this._startExpirationInterval()
this._log.info('node created', {
nodeID: this._self.nodeID
})
} | javascript | {
"resource": ""
} |
q65116 | test | function() {
var deferred;
deferred = Q.defer();
if (running.length < limit) {
running.push(deferred);
deferred.resolve();
} else {
queue.push(deferred);
}
return deferred.promise;
} | javascript | {
"resource": ""
} |
|
q65117 | test | function() {
var next;
running.pop();
if (queue.length > 0 && running.length < limit) {
switch (type) {
case "lifo":
next = queue.pop();
break;
default:
next = queue.shift();
}
running.push(next);
return next.resolve();
}
} | javascript | {
"resource": ""
} |
|
q65118 | test | function() {
var promise;
while (promise = queue.pop()) {
promise.reject("flush");
}
while (promise = running.pop()) {
promise.reject("flush");
}
} | javascript | {
"resource": ""
} |
|
q65119 | test | function(record) {
var me = this;
me._record = record;
if (record && record.data) {
me.setValues(record.data);
}
return this;
} | javascript | {
"resource": ""
} |
|
q65120 | test | function() {
var fields = [];
var getFieldsFrom = function(item) {
if (item.isField) {
fields.push(item);
}
if (item.isContainer) {
item.items.each(getFieldsFrom);
}
};
this.items.each(getFieldsFrom);
return fields;
} | javascript | {
"resource": ""
} |
|
q65121 | test | function() {
var fields = this.getFieldsArray(),
ln = fields.length,
field, i;
for (i = 0; i < ln; i++) {
field = fields[i];
if (field.isFocused) {
return field;
}
}
return null;
} | javascript | {
"resource": ""
} |
|
q65122 | test | function(point, threshold) {
if (typeof threshold == 'number') {
threshold = {x: threshold};
threshold.y = threshold.x;
}
var x = point.x,
y = point.y,
thresholdX = threshold.x,
thresholdY = threshold.y;
return (this.x <= x + thresholdX && this.x >= x - thresholdX &&
this.y <= y + thresholdY && this.y >= y - thresholdY);
} | javascript | {
"resource": ""
} |
|
q65123 | sshCommandSequence | test | function sshCommandSequence(connection, commands, fnOutput) {
var allResults = [];
var successHandler = function(nextPromise){
return function(result) {
if( result !== true) { // the first result must be ignored
allResults.push(result);
}
return nextPromise();
};
};
var errorHandler = function(nextPromise) {
return function(error) {
allResults.push(error);
return nextPromise();
};
};
// start the sequential fullfilment of the Promise chain
// The first result (true) will not be inserted in the result array, it is here
// just to start the chain.
var result = Q(true);
commands.map(function(command){
return function() {
return sshExecSingleCommand(connection, command, fnOutput);
};
}).forEach(function (f) {
result = result.then(
successHandler(f),
errorHandler(f)
);
});
// As the last result is not handled in the forEach loop, we must handle it now
return result.then(
function(finalResult){
allResults.push(finalResult);
return allResults;
},
function(error) {
allResults.push(error);
return allResults;
});
} | javascript | {
"resource": ""
} |
q65124 | replaceRefs | test | function replaceRefs(parsed, options) {
var topLevel = topLevelDeclsAndRefs(parsed),
refsToReplace = topLevel.refs.filter(ref => shouldRefBeCaptured(ref, topLevel, options)),
locallyIgnored = [];
const replaced = ReplaceVisitor.run(parsed, (node, path) => {
// cs 2016/06/27, 1a4661
// ensure keys of shorthand properties are not renamed while capturing
if (node.type === "Property"
&& refsToReplace.includes(node.key)
&& node.shorthand)
return prop(id(node.key.name), node.value);
// don't replace var refs in expressions such as "export { x }" or "export var x;"
// We make sure that those var references are defined in insertDeclarationsForExports()
if (node.type === "ExportNamedDeclaration") {
var { declaration, specifiers } = node;
if (declaration) {
if (declaration.id) locallyIgnored.push(declaration.id)
else if (declaration.declarations)
locallyIgnored.push(...declaration.declarations.map(({id}) => id))
}
specifiers && specifiers.forEach(({local}) => locallyIgnored.push(local));
return node;
}
// declaration wrapper function for assignments
// "a = 3" => "a = _define('a', 'assignment', 3, _rec)"
if (node.type === "AssignmentExpression"
&& refsToReplace.includes(node.left)
&& options.declarationWrapper)
return {
...node,
right: declarationWrapperCall(
options.declarationWrapper,
null,
literal(node.left.name),
literal("assignment"),
node.right,
options.captureObj,
options)};
return node
});
return ReplaceVisitor.run(replaced, (node, path, parent) =>
refsToReplace.includes(node) && !locallyIgnored.includes(node) ?
member(options.captureObj, node) : node);
} | javascript | {
"resource": ""
} |
q65125 | generateUniqueName | test | function generateUniqueName(declaredNames, hint) {
var unique = hint, n = 1;
while (declaredNames.indexOf(unique) > -1) {
if (n > 1000) throw new Error("Endless loop searching for unique variable " + unique);
unique = unique.replace(/_[0-9]+$|$/, "_" + (++n));
}
return unique;
} | javascript | {
"resource": ""
} |
q65126 | replaceClassDecls | test | function replaceClassDecls(parsed, options) {
if (options.classToFunction)
return classToFunctionTransform(parsed, options.classToFunction);
var topLevel = topLevelDeclsAndRefs(parsed);
if (!topLevel.classDecls.length) return parsed;
for (var i = parsed.body.length - 1; i >= 0; i--) {
var stmt = parsed.body[i];
if (stmt.id && topLevel.classDecls.includes(stmt))
parsed.body.splice(i+1, 0, assignExpr(options.captureObj, stmt.id, stmt.id, false));
}
return parsed;
} | javascript | {
"resource": ""
} |
q65127 | varDeclOrAssignment | test | function varDeclOrAssignment(parsed, declarator, kind) {
var topLevel = topLevelDeclsAndRefs(parsed),
name = declarator.id.name
return topLevel.declaredNames.indexOf(name) > -1 ?
// only create a new declaration if necessary
exprStmt(assign(declarator.id, declarator.init)) :
{
declarations: [declarator],
kind: kind || "var", type: "VariableDeclaration"
}
} | javascript | {
"resource": ""
} |
q65128 | Item | test | function Item (key, value, publisher, timestamp) {
if (!(this instanceof Item)) {
return new Item(key, value, publisher, timestamp)
}
assert(typeof key === 'string', 'Invalid key supplied')
assert(utils.isValidKey(publisher), 'Invalid publisher nodeID supplied')
if (timestamp) {
assert(typeof timestamp === 'number', 'Invalid timestamp supplied')
assert(Date.now() >= timestamp, 'Timestamp cannot be in the future')
}
this.key = key
this.value = value
this.publisher = publisher
this.timestamp = timestamp || Date.now()
} | javascript | {
"resource": ""
} |
q65129 | on | test | function on(top) {
top = typeof top === 'string' ? document.querySelector(top) : top;
var h = handle.bind(this, top);
h.once = once.bind(this, top);
return h;
} | javascript | {
"resource": ""
} |
q65130 | handleElements | test | function handleElements(elements, type, fn, capture) {
if (!elements || typeof elements.length !== 'number') throw new TypeError('Cannot bind event ' + inspect(type) + ' to ' + inspect(elements));
if (typeof type !== 'string') throw new TypeError('Event type must be a string, e.g. "click", not ' + inspect(type));
if (typeof fn !== 'function') throw new TypeError('`fn` (the function to call when the event is triggered) must be a function, not ' + inspect(fn));
if (capture !== undefined && capture !== false && capture !== true) {
throw new TypeError('`capture` must be `undefined` (defaults to `false`), `false` or `true`, not ' + inspect(capture));
}
var handles = [];
for (var i = 0; i < elements.length; i++) {
handles.push(handleElement(elements[i], type, fn, capture));
}
return function dispose() {
for (var i = 0; i < handles.length; i++) {
handles[i]();
}
};
} | javascript | {
"resource": ""
} |
q65131 | test | function(opt) {
this.disable();
if (opt) this.set(opt);
var jNode = new JSYG(this.node),
dim = jNode.getDim(),
color = jNode.fill(),
svg = jNode.offsetParent(),
id = 'idpattern'+JSYG.rand(0,5000),
g,rect,selection;
if (!color || color == 'transparent' || color == 'none') color = 'white';
if (dim.width < this.boxInit.width) this.boxInit.width = dim.width;
if (dim.height < this.boxInit.height) this.boxInit.height= dim.height;
rect = new JSYG('<rect>').fill(color);
g = new JSYG('<g>').append(rect);
new JSYG(this.pattern)
.attr({id:id,patternUnits:'userSpaceOnUse'})
.append(g).appendTo(svg);
new JSYG(this.mask)
.css('fill-opacity',0.5)
.appendTo(svg);
if (this.keepRatio) this.boxInit.height = dim.height * this.boxInit.width / dim.width;
selection = new JSYG(this.selection)
.attr(this.boxInit)
.attr('fill',"url(#"+id+")")
.appendTo(svg);
this.editor.target(selection);
this.editor.displayShadow = false;
new JSYG(this.editor.pathBox).css('fill-opacity',0);
this.editor.ctrlsDrag.enable({
bounds:0
});
this.editor.ctrlsResize.enable({
keepRatio : this.keepRatio,
bounds : 0
});
this.editor.show();
this.enabled = true;
this.update();
return this;
} | javascript | {
"resource": ""
} |
|
q65132 | without | test | function without (toRemove) {
return function (prev, curr) {
if (!Array.isArray(prev)) {
prev = !testValue(prev, toRemove)
? [ prev ]
: []
}
if (!testValue(curr, toRemove)) prev.push(curr)
return prev
}
} | javascript | {
"resource": ""
} |
q65133 | initDhtmlxToolbar | test | function initDhtmlxToolbar (container) {
var impl = null;
if (Util.isNode(container)) {
impl = new dhtmlXToolbarObject(container, SKIN);
} else if (container.type === OBJECT_TYPE.LAYOUT_CELL
|| container.type === OBJECT_TYPE.ACCORDION_CELL
|| container.type === OBJECT_TYPE.LAYOUT
|| container.type === OBJECT_TYPE.WINDOW
|| container.type === OBJECT_TYPE.TAB) {
impl = container.impl.attachToolbar();
impl.setSkin(SKIN);
} else {
throw new Error('initDhtmlxToolbar: container is not valid.');
}
return impl;
} | javascript | {
"resource": ""
} |
q65134 | test | function(data, track) {
if (track !== false) data = $track(data, track);
this.data = data;
this._dep.changed();
return this;
} | javascript | {
"resource": ""
} |
|
q65135 | test | function() {
var models = [ this ],
model = this;
while (model.parent) {
models.unshift(model = model.parent);
}
return models
} | javascript | {
"resource": ""
} |
|
q65136 | test | function(index) {
if (!_.isNumber(index) || isNaN(index)) index = 0;
if (index < 0) return this.getAllModels()[~index];
var model = this;
while (index && model) {
model = model.parent;
index--;
}
return model;
} | javascript | {
"resource": ""
} |
|
q65137 | test | function(fn) {
var index = 0,
model = this;
while (model != null) {
if (fn.call(this, model, index++)) return model;
model = model.parent;
}
} | javascript | {
"resource": ""
} |
|
q65138 | test | function(path) {
if (typeof path === "string") path = parse(path, { startRule: "path" });
if (!_.isObject(path)) throw new Error("Expecting string or object for path.");
var self = this;
this._dep.depend();
return _.reduce(path.parts, function(target, part) {
target = self._get(target, part.key);
_.each(part.children, function(k) {
if (_.isObject(k)) k = self.get(k);
target = self._get(target, k);
});
return target;
}, this.data);
} | javascript | {
"resource": ""
} |
|
q65139 | test | function(paths) {
var self = this;
if (typeof paths === "string") paths = parse(paths, { startRule: "pathQuery" });
if (!_.isArray(paths)) paths = paths != null ? [ paths ] : [];
if (!paths.length) {
var model = this.findModel(function(m) { return !_.isUndefined(m.data); });
if (model == null) return;
var val = model.data;
if (_.isFunction(val)) val = val.call(this, null);
return val;
}
return _.reduce(paths, function(result, path, index) {
var model = self,
scope = true,
val;
if (path.type === "root") {
model = self.getRootModel();
} else if (path.type === "parent") {
model = self.getModelAtOffset(path.distance);
scope = false;
} else if (path.type === "all") {
scope = false;
}
if (model == null) return;
while (_.isUndefined(val) && model != null) {
val = model.getLocal(path);
model = model.parent;
if (scope) break;
}
if (_.isFunction(val)) {
val = val.call(self, index === 0 ? null : result);
}
return val;
}, void 0);
} | javascript | {
"resource": ""
} |
|
q65140 | test | function(done) {
crypto.randomBytes(20, function(err, buffer) {
var token = buffer.toString('hex');
done(err, token);
});
} | javascript | {
"resource": ""
} |
|
q65141 | test | function(token, done) {
if (req.body.username) {
User.findOne({
username: req.body.username
}, '-salt -password', function(err, user) {
if (!user) {
return res.status(400).send({
message: 'No account with that username has been found'
});
} else if (user.provider !== 'local') {
return res.status(400).send({
message: 'It seems like you signed up using your ' + user.provider + ' account'
});
} else {
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
}
});
} else {
return res.status(400).send({
message: 'Username field must not be blank'
});
}
} | javascript | {
"resource": ""
} |
|
q65142 | test | function(emailHTML, user, done) {
var smtpTransport = nodemailer.createTransport(config.mailer.options);
var mailOptions = {
to: user.email,
from: config.mailer.from,
subject: 'Your password has been changed',
html: emailHTML
};
smtpTransport.sendMail(mailOptions, function(err) {
done(err, 'done');
});
} | javascript | {
"resource": ""
} |
|
q65143 | sortIssues | test | function sortIssues(issues) {
var sorted;
// Issues might be pre-arranged by super/sub tasks.
if (Object.keys(issues).indexOf('supers') > -1) {
// Network format issue sort
issues.supers = _.sortBy(issues.supers, function(issue) {
return new Date(issue.updated_at);
}).reverse();
issues.singletons = _.sortBy(issues.singletons, function(issue) {
return new Date(issue.updated_at);
}).reverse();
sorted = issues;
} else {
sorted = _.sortBy(issues, function(issue) {
return new Date(issue.updated_at);
}).reverse();
}
return sorted;
} | javascript | {
"resource": ""
} |
q65144 | deduplicateCollaborators | test | function deduplicateCollaborators(collaborators) {
var foundLogins = [];
return _.filter(collaborators, function (collaborator) {
var duplicate = false
, login = collaborator.login;
if (foundLogins.indexOf(login) > -1) {
duplicate = true;
} else {
foundLogins.push(login);
}
return ! duplicate;
});
} | javascript | {
"resource": ""
} |
q65145 | extractSuperIssueSubTaskNumbers | test | function extractSuperIssueSubTaskNumbers(superIssue) {
var matches = superIssue.body.match(markdownTasksRegex)
, subTaskIds = [];
_.each(matches, function(line) {
var match = line.match(subtaskRegex);
if (match) {
subTaskIds.push(parseInt(match[3]));
}
});
return subTaskIds;
} | javascript | {
"resource": ""
} |
q65146 | formatIssues | test | function formatIssues(format, issues) {
var formattedIssues
, partition
, superIssues
, singletonIssues
, removedSubtasks = [];
if (format == 'network') {
formattedIssues = {
supers: []
, singletons: []
, all: issues
};
partition = _.partition(issues, function(issue) {
return _.find(issue.labels, function(label) {
return label.name == 'super';
});
});
superIssues = partition.shift();
singletonIssues = partition.shift();
_.each(superIssues, function(superIssue) {
var subTaskNumbers = extractSuperIssueSubTaskNumbers(superIssue);
superIssue.subtasks = _.filter(singletonIssues, function(issue) {
var isSubtask = _.contains(subTaskNumbers, issue.number);
if (isSubtask) {
removedSubtasks.push(issue.number);
}
return isSubtask;
});
});
formattedIssues.supers = superIssues;
_.each(singletonIssues, function(issue) {
if (! _.contains(removedSubtasks, issue.number)) {
formattedIssues.singletons.push(issue);
}
});
} else {
formattedIssues = issues;
}
return formattedIssues;
} | javascript | {
"resource": ""
} |
q65147 | mergeIssuesAndPrs | test | function mergeIssuesAndPrs(issues, prs) {
_.each(issues, function(issue) {
var targetPr
, targetPrIndex = _.findIndex(prs, function(pr) {
return pr && pr.number == issue.number;
});
if (targetPrIndex > -1) {
targetPr = prs[targetPrIndex];
prs[targetPrIndex] = _.merge(targetPr, issue);
}
});
return prs;
} | javascript | {
"resource": ""
} |
q65148 | Sprinter | test | function Sprinter(username, password, repoSlugs, cache) {
if (! username) {
throw new Error('Missing username.');
}
if (! password) {
throw new Error('Missing password.');
}
if (! repoSlugs) {
throw new Error('Missing repositories.');
}
this.username = username;
this.password = password;
// Verify required configuration elements.
this.repos = convertSlugsToObjects(repoSlugs);
this.gh = new GitHubApi({
version: '3.0.0'
, timeout: 5000
});
this.gh.authenticate({
type: 'basic'
, username: this.username
, password: this.password
});
this._CACHE = {};
this.setCacheDuration(cache);
this._setupCaching();
} | javascript | {
"resource": ""
} |
q65149 | getFetchByStateCallback | test | function getFetchByStateCallback(callback) {
return function(err, data) {
if (err) {
asyncErrors.push(err);
}
callback(null, data);
};
} | javascript | {
"resource": ""
} |
q65150 | listAvailables | test | function listAvailables(forceRefresh) {
forceRefresh && (adaptersCache = []);
if( adaptersCache.length ){
return adaptersCache;
}
adaptersCache = fs.readdirSync(__dirname).filter(function(fileOrDirName){
return isDir(__dirname + '/' + fileOrDirName);
});
return adaptersCache;
} | javascript | {
"resource": ""
} |
q65151 | readConfig | test | function readConfig(adapterName, path){
var adapter = getAdapterInstance(adapterName);
return adapter.configLoader(normalizeAdapterConfigPath(adapter, path));
} | javascript | {
"resource": ""
} |
q65152 | writeConfig | test | function writeConfig(adapterName, path, config){
var adapter = getAdapterInstance(adapterName);
return adapter.configWriter(normalizeAdapterConfigPath(adapter, path), config);
} | javascript | {
"resource": ""
} |
q65153 | handleFiles | test | function handleFiles(files) {
files.forEach(function(f) {
f.src.filter(srcExists).map(function(filepath) {
var pathInfo = getPathInfo(filepath, f.dest),
context = getContext(f.context, pathInfo);
renderFile(pathInfo.outfile, filepath, context);
});
});
} | javascript | {
"resource": ""
} |
q65154 | handleI18nFiles | test | function handleI18nFiles(files) {
options.locales.forEach(function(locale) {
grunt.registerTask('swigtemplatesSubtask-' + locale, function() {
var done = this.async();
var translatorFactory = options.translateFunction(locale);
Q.when(translatorFactory, function(translator) { doTranslations(files, locale, translator) }).done(done);
});
grunt.task.run('swigtemplatesSubtask-' + locale);
});
} | javascript | {
"resource": ""
} |
q65155 | getContext | test | function getContext(context, pathInfo) {
var globalContext,
templateContext;
try {
globalContext = grunt.file.readJSON(path.join(options.templatesDir, "global.json"));
} catch(err) {
globalContext = {};
}
try {
templateContext = grunt.file.readJSON(path.join(pathInfo.dirName, pathInfo.outfileName) + ".json");
} catch(err) {
templateContext = {};
}
return _.extend({}, globalContext, templateContext, options.defaultContext, context);
} | javascript | {
"resource": ""
} |
q65156 | render | test | function render(url) {
return async page => {
try {
const template = `${page.template || 'schedule'}.hbs`;
// Load template and compile
const filePath = path.join(
process.cwd(),
config.theme || 'theme',
config.template || 'templates',
template,
);
const output = Handlebars.compile(await fs.readFile(filePath, 'utf-8'))(page);
await fs.ensureDir(outputDir);
// if home page skip else create page dir
const dir = url !== 'index' ? path.join(outputDir, url) : outputDir;
await fs.ensureDir(dir);
await fs.writeFile(path.join(dir, 'index.html'), output, 'utf8');
} catch (err) {
throw err;
}
};
} | javascript | {
"resource": ""
} |
q65157 | isNamedFunction | test | function isNamedFunction(node)
{
if (node.id)
return true;
const { parent } = node;
const { type } = parent;
const namedFunction =
type === 'MethodDefinition' ||
type === 'Property' && (parent.kind === 'get' || parent.kind === 'set' || parent.method);
return namedFunction;
} | javascript | {
"resource": ""
} |
q65158 | getConfigForFunction | test | function getConfigForFunction(node)
{
if (isNamedFunction(node))
return 'never';
if (node.type === 'ArrowFunctionExpression')
{
// Always ignore non-async functions and arrow functions without parens, e.g.
// `async foo => bar`.
if
(
!node.async ||
!astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, { skip: 1 }))
)
return 'ignore';
}
return 'always';
} | javascript | {
"resource": ""
} |
q65159 | checkFunction | test | function checkFunction(node)
{
const functionConfig = getConfigForFunction(node);
if (functionConfig === 'ignore')
return;
const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const leftToken = sourceCode.getTokenBefore(rightToken);
const text =
sourceCode
.text
.slice(leftToken.range[1], rightToken.range[0])
.replace(/\/\*[^]*?\*\//g, '');
if (astUtils.LINEBREAK_MATCHER.test(text))
return;
const hasSpacing = /\s/.test(text);
if (hasSpacing && functionConfig === 'never')
{
const report =
{
node,
loc: leftToken.loc.end,
message: 'Unexpected space before function parentheses.',
fix: fixer => fixer.removeRange([leftToken.range[1], rightToken.range[0]]),
};
context.report(report);
}
else if (!hasSpacing && functionConfig === 'always')
{
const report =
{
node,
loc: leftToken.loc.end,
message: 'Missing space before function parentheses.',
fix: fixer => fixer.insertTextAfter(leftToken, ' '),
};
context.report(report);
}
} | javascript | {
"resource": ""
} |
q65160 | test | function(config) {
var me = this;
//<debug warn>
for (var configName in config) {
if (me.self.prototype.config && !(configName in me.self.prototype.config)) {
me[configName] = config[configName];
Ext.Logger.warn('Applied config as instance property: "' + configName + '"', me);
}
}
//</debug>
me.initConfig(config);
} | javascript | {
"resource": ""
} |
|
q65161 | bindEventMap | test | function bindEventMap(eventMap, eventEmitter) {
var eventNames = Object.keys(eventMap);
eventNames.map(function (eventName) {
eventEmitter.on(eventName, eventMap[eventName]);
});
} | javascript | {
"resource": ""
} |
q65162 | test | function(delay, newFn, newScope, newArgs) {
var me = this;
//cancel any existing queued functions
me.cancel();
//set all the new configurations
if (Ext.isNumber(delay)) {
me.setDelay(delay);
}
if (Ext.isFunction(newFn)) {
me.setFn(newFn);
}
if (newScope) {
me.setScope(newScope);
}
if (newScope) {
me.setArgs(newArgs);
}
//create the callback method for this delayed task
var call = function() {
me.getFn().apply(me.getScope(), me.getArgs() || []);
me.cancel();
};
me.setInterval(setInterval(call, me.getDelay()));
} | javascript | {
"resource": ""
} |
|
q65163 | test | function(success, operation, request, response, callback, scope) {
var me = this,
action = operation.getAction(),
reader, resultSet;
if (success === true) {
reader = me.getReader();
try {
resultSet = reader.process(me.getResponseResult(response));
} catch(e) {
operation.setException(e.message);
me.fireEvent('exception', me, response, operation);
return;
}
// This could happen if the model was configured using metaData
if (!operation.getModel()) {
operation.setModel(this.getModel());
}
if (operation.process(action, resultSet, request, response) === false) {
me.setException(operation, response);
me.fireEvent('exception', me, response, operation);
}
} else {
me.setException(operation, response);
/**
* @event exception
* Fires when the server returns an exception
* @param {Ext.data.proxy.Proxy} this
* @param {Object} response The response from the AJAX request
* @param {Ext.data.Operation} operation The operation that triggered request
*/
me.fireEvent('exception', this, response, operation);
}
//this callback is the one that was passed to the 'read' or 'write' function above
if (typeof callback == 'function') {
callback.call(scope || me, operation);
}
me.afterRequest(request, success);
} | javascript | {
"resource": ""
} |
|
q65164 | test | function(operation, response) {
if (Ext.isObject(response)) {
operation.setException({
status: response.status,
statusText: response.statusText
});
}
} | javascript | {
"resource": ""
} |
|
q65165 | test | function(request) {
var me = this,
url = me.getUrl(request);
//<debug>
if (!url) {
Ext.Logger.error("You are using a ServerProxy but have not supplied it with a url.");
}
//</debug>
if (me.getNoCache()) {
url = Ext.urlAppend(url, Ext.String.format("{0}={1}", me.getCacheString(), Ext.Date.now()));
}
return url;
} | javascript | {
"resource": ""
} |
|
q65166 | test | function(newDateFormat, oldDateFormat) {
var value = this.getValue();
if (newDateFormat != oldDateFormat && Ext.isDate(value)) {
this.getComponent().setValue(Ext.Date.format(value, newDateFormat || Ext.util.Format.defaultDateFormat));
}
} | javascript | {
"resource": ""
} |
|
q65167 | test | function(picker, value) {
var me = this,
oldValue = me.getValue();
me.setValue(value);
me.fireEvent('select', me, value);
me.onChange(me, value, oldValue);
} | javascript | {
"resource": ""
} |
|
q65168 | clone | test | function clone (obj) {
var newObj = {};
// Return a new obj if no `obj` passed in
if (!obj || typeof obj !== 'object' || Array.isArray(obj))
return newObj;
for (var prop in obj)
newObj[prop] = obj[prop];
return newObj;
} | javascript | {
"resource": ""
} |
q65169 | ImpulseBin | test | function ImpulseBin() {
this.settings = {
adapter: 'commander',
quietOption: 'quiet',
requiredOptionTmpl: '--%s is required',
verboseOption: 'verbose',
verboseLogName: '[verbose]',
stdoutLogName: '[stdout]',
stderrLogName: '[stderr]'
};
this.console = require('long-con').create();
// Assigned in run():
this.adapter = null;
this.options = null;
this.provider = null;
} | javascript | {
"resource": ""
} |
q65170 | test | function(config) {
var me = this,
currentConfig = me.config,
id;
me.onInitializedListeners = [];
me.initialConfig = config;
if (config !== undefined && 'id' in config) {
id = config.id;
}
else if ('id' in currentConfig) {
id = currentConfig.id;
}
else {
id = me.getId();
}
me.id = id;
me.setId(id);
Ext.ComponentManager.register(me);
me.initElement();
me.initConfig(me.initialConfig);
me.refreshSizeState = me.doRefreshSizeState;
me.refreshFloating = me.doRefreshFloating;
if (me.refreshSizeStateOnInitialized) {
me.refreshSizeState();
}
if (me.refreshFloatingOnInitialized) {
me.refreshFloating();
}
me.initialize();
me.triggerInitialized();
/**
* Force the component to take up 100% width and height available, by adding it to {@link Ext.Viewport}.
* @cfg {Boolean} fullscreen
*/
if (me.config.fullscreen) {
me.fireEvent('fullscreen', me);
}
me.fireEvent('initialize', me);
} | javascript | {
"resource": ""
} |
|
q65171 | test | function(className, /* private */ force) {
var oldCls = this.getCls(),
newCls = (oldCls) ? oldCls.slice() : [];
if (force || newCls.indexOf(className) == -1) {
newCls.push(className);
} else {
Ext.Array.remove(newCls, className);
}
this.setCls(newCls);
return this;
} | javascript | {
"resource": ""
} |
|
q65172 | test | function(animation) {
this.setCurrentAlignmentInfo(null);
/*
if(this.activeAnimation) {
this.activeAnimation.on({
animationend: function(){
this.hide(animation);
},
scope: this,
single: true
});
return this;
}
*/
if (!this.getHidden()) {
if (animation === undefined || (animation && animation.isComponent)) {
animation = this.getHideAnimation();
}
if (animation) {
if (animation === true) {
animation = 'fadeOut';
}
this.onBefore({
hiddenchange: 'animateFn',
scope: this,
single: true,
args: [animation]
});
}
this.setHidden(true);
}
return this;
} | javascript | {
"resource": ""
} |
|
q65173 | test | function(animation) {
if(this.activeAnimation) {
this.activeAnimation.on({
animationend: function(){
this.show(animation);
},
scope: this,
single: true
});
return this;
}
var hidden = this.getHidden();
if (hidden || hidden === null) {
if (animation === true) {
animation = 'fadeIn';
}
else if (animation === undefined || (animation && animation.isComponent)) {
animation = this.getShowAnimation();
}
if (animation) {
this.beforeShowAnimation();
this.onBefore({
hiddenchange: 'animateFn',
scope: this,
single: true,
args: [animation]
});
}
this.setHidden(false);
}
return this;
} | javascript | {
"resource": ""
} |
|
q65174 | test | function(width, height) {
if (width != undefined) {
this.setWidth(width);
}
if (height != undefined) {
this.setHeight(height);
}
} | javascript | {
"resource": ""
} |
|
q65175 | test | function(component, alignment) {
var me = this,
viewport = Ext.Viewport,
parent = me.getParent();
me.setVisibility(false);
if (parent !== viewport) {
viewport.add(me);
}
me.show();
me.on({
hide: 'onShowByErased',
destroy: 'onShowByErased',
single: true,
scope: me
});
viewport.on('resize', 'alignTo', me, { args: [component, alignment] });
me.alignTo(component, alignment);
me.setVisibility(true);
} | javascript | {
"resource": ""
} |
|
q65176 | test | function (component, alignment){
var alignToElement = component.isComponent ? component.renderElement : component,
alignToBox = alignToElement.getPageBox(),
element = this.renderElement,
box = element.getPageBox(),
stats = {
alignToBox: alignToBox,
alignment: alignment,
top: alignToBox.top,
left: alignToBox.left,
alignToWidth: alignToBox.width,
alignToHeight: alignToBox.height,
width: box.width,
height: box.height
},
currentAlignmentInfo = this.getCurrentAlignmentInfo(),
isAligned = true;
if (!Ext.isEmpty(currentAlignmentInfo)) {
Ext.Object.each(stats, function(key, value) {
if (!Ext.isObject(value) && currentAlignmentInfo[key] != value) {
isAligned = false;
return false;
}
return true;
});
} else {
isAligned = false;
}
return {isAligned: isAligned, stats: stats};
} | javascript | {
"resource": ""
} |
|
q65177 | test | function(alignmentInfo) {
this.$currentAlignmentInfo = Ext.isEmpty(alignmentInfo) ? null : Ext.merge({}, alignmentInfo.stats ? alignmentInfo.stats : alignmentInfo);
} | javascript | {
"resource": ""
} |
|
q65178 | test | function(selector) {
var result = this.parent;
if (selector) {
for (; result; result = result.parent) {
if (Ext.ComponentQuery.is(result, selector)) {
return result;
}
}
}
return result;
} | javascript | {
"resource": ""
} |
|
q65179 | test | function() {
this.destroy = Ext.emptyFn;
var parent = this.getParent(),
referenceList = this.referenceList,
i, ln, reference;
this.isDestroying = true;
Ext.destroy(this.getTranslatable(), this.getPlugins());
// Remove this component itself from the container if it's currently contained
if (parent) {
parent.remove(this, false);
}
// Destroy all element references
for (i = 0, ln = referenceList.length; i < ln; i++) {
reference = referenceList[i];
this[reference].destroy();
delete this[reference];
}
Ext.destroy(this.innerHtmlElement);
this.setRecord(null);
this.callSuper();
Ext.ComponentManager.unregister(this);
} | javascript | {
"resource": ""
} |
|
q65180 | test | function (list, index, target, record, e) {
var me = this,
store = list.getStore(),
node = store.getAt(index);
me.fireEvent('itemtap', this, list, index, target, record, e);
if (node.isLeaf()) {
me.fireEvent('leafitemtap', this, list, index, target, record, e);
me.goToLeaf(node);
}
else {
this.goToNode(node);
}
} | javascript | {
"resource": ""
} |
|
q65181 | test | function () {
var me = this,
node = me.getLastNode(),
detailCard = me.getDetailCard(),
detailCardActive = detailCard && me.getActiveItem() == detailCard,
lastActiveList = me.getLastActiveList();
this.fireAction('back', [this, node, lastActiveList, detailCardActive], 'doBack');
} | javascript | {
"resource": ""
} |
|
q65182 | test | function (node) {
if (!node.isLeaf()) {
throw new Error('goToLeaf: passed a node which is not a leaf.');
}
var me = this,
card = me.getDetailCard(node),
container = me.getDetailContainer(),
sharedContainer = container == this,
layout = me.getLayout(),
animation = (layout) ? layout.getAnimation() : false;
if (card) {
if (container.getItems().indexOf(card) === -1) {
container.add(card);
}
if (sharedContainer) {
if (me.getActiveItem() instanceof Ext.dataview.List) {
me.setLastActiveList(me.getActiveItem());
}
me.setLastNode(node);
}
if (animation) {
animation.setReverse(false);
}
container.setActiveItem(card);
me.syncToolbar();
}
} | javascript | {
"resource": ""
} |
|
q65183 | hoistFunctions | test | function hoistFunctions(program) {
var functions = [];
var body = [];
for (let line of program.body) {
if (line.type === 'ExportDefaultDeclaration') {
if (line.declaration.type === 'FunctionDeclaration') {
functions.push(line);
} else {
body.push(line);
}
continue;
}
if (line.type === 'ExportNamedDeclaration') {
if (!!line.declaration &&
line.declaration.type === 'FunctionDeclaration') {
functions.push(line);
} else {
body.push(line);
}
continue;
}
if (line.type === 'FunctionDeclaration') {
functions.push(line);
} else {
body.push(line);
}
}
return makeProgram([...functions, ...body]);
} | javascript | {
"resource": ""
} |
q65184 | parseVehicleID | test | function parseVehicleID($, item) {
let fields = $(item).find('td');
let id = $(fields[1]).find('a').attr('href').replace('Detail.aspx?id=', '');
return id;
} | javascript | {
"resource": ""
} |
q65185 | formatDetails | test | function formatDetails(details) {
let result = {
results: details,
count: details.length,
time: new Date().toISOString()
};
return result;
} | javascript | {
"resource": ""
} |
q65186 | getByID | test | function getByID(id) {
var url = `${APP_BASE_URL}Detail.aspx?id=${id}`;
return request(url)
.then(function(body) {
let $ = cheerio.load(body);
let info = {
url: url,
id: id
};
$('table#searchTableResults tr').each((i, item) => {
let span = $(item).find('span');
let key = $(span).attr('id').replace('ctl00_Application_lbl', '').toLowerCase();
let value = $(span).text().trim();
info[translations[key] || key] = value;
});
info.stolendate = getStandardizedDateStr(info.stolendate);
return info;
});
} | javascript | {
"resource": ""
} |
q65187 | test | function(config) {
if (!config.callback) {
Ext.Logger.error('You must specify a `callback` for `#canMakePayments` to work.');
return false;
}
Ext.device.Communicator.send({
command: 'Purchase#canMakePayments',
callbacks: {
callback: function(flag) {
config.callback.call(config.scope || this, flag);
}
},
scope: config.scope || this
});
} | javascript | {
"resource": ""
} |
|
q65188 | test | function(config) {
if (!config.success) {
Ext.Logger.error('You must specify a `success` callback for `#purchase` to work.');
return false;
}
if (!config.failure) {
Ext.Logger.error('You must specify a `failure` callback for `#purchase` to work.');
return false;
}
Ext.device.Communicator.send({
command: 'Purchase#purchase',
identifier: this.get('productIdentifier'),
callbacks: {
success: config.success,
failure: config.failure
},
scope: config.scope || this
});
} | javascript | {
"resource": ""
} |
|
q65189 | test | function(config) {
var me = this;
if (!config.success) {
Ext.Logger.error('You must specify a `success` callback for `#complete` to work.');
return false;
}
if (!config.failure) {
Ext.Logger.error('You must specify a `failure` callback for `#complete` to work.');
return false;
}
if (this.get('state') != 'charged') {
config.failure.call(config.scope || this, 'purchase is not charged');
}
Ext.device.Communicator.send({
command: 'Purchase#complete',
identifier: me.get('transactionIdentifier'),
callbacks: {
success: function() {
me.set('state', 'completed');
config.success.call(config.scope || this);
},
failure: function() {
me.set('state', 'charged');
config.failure.call(config.scope || this);
}
},
scope: config.scope || this
});
} | javascript | {
"resource": ""
} |
|
q65190 | test | function (key) {
this.key = key;
this.keyType = key.split(" ")[0];
this.rawkey = key.split(" ")[1];
try{
this.keyComment = key.split(" ")[2];
} catch(err){
this.keyComment = null;
}
this.byteArray = this._stringToBytes(atob(this.rawkey));
this.slicedArray = [];
this.wordLength = 4;
this._load();
} | javascript | {
"resource": ""
} |
|
q65191 | test | function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
Ctor.prototype = sourceFunc.prototype;
var self = new Ctor;
Ctor.prototype = null;
var result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
} | javascript | {
"resource": ""
} |
|
q65192 | test | function(e) {
var me = this,
oldChecked = me._checked,
newChecked = me.getChecked();
// only fire the event when the value changes
if (oldChecked != newChecked) {
if (newChecked) {
me.fireEvent('check', me, e);
} else {
me.fireEvent('uncheck', me, e);
}
me.fireEvent('change', me, newChecked, oldChecked);
}
} | javascript | {
"resource": ""
} |
|
q65193 | test | function() {
var values = [];
this.getSameGroupFields().forEach(function(field) {
if (field.getChecked()) {
values.push(field.getValue());
}
});
return values;
} | javascript | {
"resource": ""
} |
|
q65194 | test | function(values) {
this.getSameGroupFields().forEach(function(field) {
field.setChecked((values.indexOf(field.getValue()) !== -1));
});
return this;
} | javascript | {
"resource": ""
} |
|
q65195 | test | function() {
var me = this,
container = me.container;
if (!me.getStore()) {
if (!me.hasLoadedStore && !me.getDeferEmptyText()) {
me.showEmptyText();
}
return;
}
if (container) {
me.fireAction('refresh', [me], 'doRefresh');
}
} | javascript | {
"resource": ""
} |
|
q65196 | processParams | test | function processParams(paramsString) {
var individualParams = paramsString.split("&"),
resultObject = {};
individualParams.forEach(function(item) {
var itemParts = item.split("="),
paramName = itemParts[0],
paramValue = decodeURIComponent(itemParts[1] || "");
var paramObject = {};
paramObject[paramName] = paramValue;
$.extend(resultObject, paramObject);
});
return resultObject;
} | javascript | {
"resource": ""
} |
q65197 | test | function(config) {
if (!this._store) {
this._store = [
{
first: 'Robert',
last: 'Dougan',
emails: {
work: 'rob@sencha.com'
}
},
{
first: 'Jamie',
last: 'Avins',
emails: {
work: 'jamie@sencha.com'
}
}
];
}
config.success.call(config.scope || this, this._store);
} | javascript | {
"resource": ""
} |
|
q65198 | Collection | test | function Collection(options) {
if (!(this instanceof Collection)){
return new Collection(options);
}
options = options || {};
if (options instanceof Array) {
this.modelType = undefined;
this.items = options;
} else {
this.modelType = options.modelType;
this.items = options.items || [];
if (!(this.items instanceof Array)) {
throw new CollectionException('Items must be an array');
}
}
} | javascript | {
"resource": ""
} |
q65199 | find | test | function find(filter) {
var item;
var i;
var ilen;
var keys;
var key;
var k;
var klen;
var found;
if (filter instanceof Function) {
for (i = 0, ilen = this.items.length; i < ilen; ++i) {
item = this.items[i];
if (filter(item, i)) {
return item;
}
}
} else if (filter !== null && filter !== undefined) {
if (typeof filter === 'object') {
keys = Object.keys(filter);
klen = keys.length;
for (i = 0, ilen = this.items.length; i < ilen; ++i) {
item = this.items[i];
found = true;
for (k = 0; k < klen && found; ++k) {
key = keys[k];
if (filter[key] !== item[key]) {
found = false;
}
}
if (found) {
return item;
}
}
} else if (this.modelType) {
keys = Object.keys(this.modelType.attributes);
klen = keys.length;
for (i = 0, ilen = this.items.length; i < ilen; ++i) {
item = this.items[i];
found = false;
for (k = 0; k < klen && !found; ++k) {
key = keys[k];
if (filter === item[key]) {
found = true;
}
}
if (found) {
return item;
}
}
} else {
for (i = 0, ilen = this.items.length; i < ilen; ++i) {
item = this.items[i];
found = false;
keys = Object.keys(item);
for (k = 0, klen = keys.length; k < klen && !found; ++k) {
key = keys[k];
if (filter === item[key]) {
found = true;
}
}
if (found) {
return item;
}
}
}
}
return undefined;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.