_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6900
|
driver
|
train
|
function driver(options, fn) {
if ('function' == typeof options) fn = options, options = {};
options = options || {};
fn = fn || electron;
var nightmare = new Nightmare(options);
return function nightmare_driver(ctx, done) {
if (ctx !=null) {
debug('goingto %s', ctx.url);
nightmare
.on('page', function (type, message, stack) {
if (type == 'error')
debug('page error: %s', message);
})
.on('did-fail-load', function (event, errorCode, errorDescription) {
debug('failed to load with error %s: %s', errorCode, errorDescription);
return done(new Error(errorDescription))
})
.on('did-get-redirect-request', function (event, oldUrl, newUrl, isMainFrame) {
if (normalize(oldUrl) == normalize(ctx.url)) {
debug('redirect: %s', newUrl);
ctx.url = newUrl;
}
})
.on('will-navigate', function (url) {
if (normalize(url) == normalize(ctx.url)) {
debug('redirect: %s', url);
ctx.url = url;
}
})
.on('did-get-response-details', function (event, status, newUrl, originalUrl, httpResponseCode, requestMethod, referrer, headers) {
if (normalize(originalUrl) == normalize(ctx.url)) {
debug('redirect: %s', newUrl);
ctx.url = newUrl;
}
;
if (normalize(newUrl) == normalize(ctx.url) && httpResponseCode == 200) {
debug('got response from %s: %s', ctx.url, httpResponseCode);
ctx.status = httpResponseCode;
}
;
})
.on('did-finish-load', function () {
debug('finished loading %s', ctx.url);
})
wrapfn(fn, select)(ctx, nightmare);
}
function select(err, ret) {
if (err) return done(err);
nightmare
.evaluate(function() {
return document.documentElement.outerHTML;
})
nightmare
.then(function(body) {
ctx.body = body;
debug('%s - %s', ctx.url, ctx.status);
done(null, ctx);
})
};
if (ctx == null || ctx == undefined) {
debug('attempting to shut down nightmare instance gracefully');
// put bogus message in the queue so nightmare end will execute
nightmare.viewport(1,1);
// force shutdown and disconnect from electron
nightmare.
end().
then(function(body) {
debug('gracefully shut down nightmare instance ');
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6901
|
combineChangesets
|
train
|
function combineChangesets (changesets) {
const actions = changesets.map((changeset) => changeset.apply)
const combinedAction = function () {
const args = arguments
return actions.reduce((promise, action) => (
promise.then(() => action.apply(null, args))
), Promise.resolve())
}
return createChangeset(combinedAction)
}
|
javascript
|
{
"resource": ""
}
|
q6902
|
isDataSource
|
train
|
function isDataSource( image ) {
const source = (typeof image === "string" ? image : image.src).substr(0, 5);
// base 64 string contains data-attribute, the MIME type and then the content, e.g. :
// e.g. "data:image/png;base64," for a typical PNG, Blob string contains no MIME, e.g.:
// blob:http://localhost:9001/46cc7e56-cf2a-7540-b515-1d99dfcb2ad6
return source === "data:" || source === "blob:";
}
|
javascript
|
{
"resource": ""
}
|
q6903
|
anyBase
|
train
|
function anyBase(srcAlphabet, dstAlphabet) {
var converter = new Converter(srcAlphabet, dstAlphabet);
/**
* Convert function
*
* @param {string|Array} number
*
* @return {string|Array} number
*/
return function (number) {
return converter.convert(number);
}
}
|
javascript
|
{
"resource": ""
}
|
q6904
|
train
|
function (fn, context, rate, warningThreshold) {
var queue = [],
timeout;
function next () {
if (queue.length === 0) {
timeout = null;
return;
}
fn.apply(context, queue.shift());
timeout = setTimeout(next, rate);
}
return function () {
if (!timeout) {
timeout = setTimeout(next, rate);
fn.apply(context, arguments);
return;
}
queue.push(arguments);
if (queue.length * rate > warningThreshold) {
console.warn("[WARNING] Rate limited function call will be delayed by", ((queue.length * rate) / 1000).toFixed(3), "secs");
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q6905
|
train
|
function (name, fn, ctx) {
assert(isString(name), 'EventEmitter#on: name is not a string');
assert(isFunction(fn), 'EventEmitter#on: fn is not a function');
// If the context is not passed, use `this`.
ctx = ctx || this;
// Push to private lists of listeners.
this._listeners.push({
name: name,
fn: fn,
ctx: ctx
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6906
|
train
|
function (name, fn, ctx) {
// If the context is not passed, use `this`.
ctx = ctx || this;
var self = this;
function onHandler() {
fn.apply(ctx, arguments);
self.off(name, onHandler);
}
this.on(name, onHandler, ctx);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6907
|
train
|
function (name, fn) {
this._listeners = !name
? []
: filter(this._listeners, function (listener) {
if (listener.name !== name) {
return true;
} else {
if (isFunction(fn)) {
return listener.fn !== fn;
} else {
return false;
}
}
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6908
|
train
|
function (name, params) {
assert(isString(name), 'EventEmitter#emit: name is not a string');
forEach(this._listeners, function (event) {
if (event.name === name) {
event.fn.call(event.ctx, params);
}
// Special behaviour for wildcard - invoke each event handler.
var isWildcard = (/^all|\*$/).test(event.name);
if (isWildcard) {
event.fn.call(event.ctx, name, params);
}
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6909
|
getElementBoundingRect
|
train
|
function getElementBoundingRect(elementSelector) {
/**
* @param {Window} win
* @param {Object} [dims]
* @returns {Object}
*/
function computeFrameOffset(win, dims) {
// initialize our result variable
dims = dims || {
left: win.pageXOffset,
top: win.pageYOffset
};
// add the offset & recurse up the frame chain
var frame = win.frameElement;
if (frame) {
var rect = frame.getBoundingClientRect();
dims.left += rect.left + frame.contentWindow.pageXOffset;
dims.top += rect.top + frame.contentWindow.pageYOffset;
if (win !== window.top) {
computeFrameOffset(win.parent, dims);
}
}
return dims;
}
/**
* @param {HTMLElement} element
* @param {Object} frameOffset
* @returns {Object}
*/
function computeElementRect(element, frameOffset) {
var rect = element.getBoundingClientRect();
return {
left: rect.left + frameOffset.left,
right: rect.right + frameOffset.left,
top: rect.top + frameOffset.top,
bottom: rect.bottom + frameOffset.top,
width: rect.width,
height: rect.height
};
}
var element = document.querySelectorAll(elementSelector)[0];
if (element) {
var frameOffset = computeFrameOffset(window);
var elementRect = computeElementRect(element, frameOffset);
return elementRect;
}
}
|
javascript
|
{
"resource": ""
}
|
q6910
|
reduxifyReducer
|
train
|
function reduxifyReducer (reducer, collectionName = null) {
return (state = [], action) => {
const collection = createReduxifyCollection(state, collectionName)
const changeset = reducer(collection, action)
// the changesets returned by the reduxify collections are just plain synchronous methods
return changeset && changeset !== collection
? applyChangeset(state, changeset)
: state
}
function applyChangeset (state, changeset) {
if (typeof changeset !== 'function') {
console.error('Reduxify changeset is a plain function. Instead got:', changeset)
throw new Error('Reduxify changeset is a plain function.')
}
// the changesets returned by the reduxify collections are just plain synchronous methods
return changeset(state)
}
}
|
javascript
|
{
"resource": ""
}
|
q6911
|
NoEmpty
|
train
|
function NoEmpty(type) {
type = typeof type == 'string' ?
Block.create({
type,
nodes: [
Text.create()
]
}) : type;
const onBeforeChange = (state) => {
const { document } = state;
// If document is not empty, it continues
if (!document.nodes.isEmpty()) {
return;
}
// Reset the state
return State.create({
document: Document.create({
nodes: [type]
})
});
};
return {
onBeforeChange
};
}
|
javascript
|
{
"resource": ""
}
|
q6912
|
onRequest
|
train
|
function onRequest (request, sender, sendResponse) {
// Show the page action for the tab that the sender (content script) was on.
chrome.pageAction.show(sender.tab.id)
var files = request.files
if (request.action === 'load') {
var rules = []
for (var file in files) {
var regex
var isKnownFile =
prevFiles[sender.tab.id] && prevFiles[sender.tab.id][file]
if (isKnownFile) {
if (prevFiles[sender.tab.id][file] === files[file]) {
// We can skip this rule if the timestamp hasn't change.
continue
}
regex = '^([^\\?]*)\\?' + prevFiles[sender.tab.id][file] + '$'
} else {
regex = '^([^\\?]*)$'
}
var actions = [
new chrome.declarativeWebRequest.RedirectByRegEx({
from: regex,
to: '$1?' + files[file]
})
]
if (!isKnownFile) { // is new file
actions.push(
new chrome.declarativeWebRequest.RemoveResponseHeader(
{name: 'Cache-Control'}))
actions.push(
new chrome.declarativeWebRequest.AddResponseHeader(
{name: 'Cache-Control', value: 'no-cache'}))
}
rules.push({
conditions: [
new chrome.declarativeWebRequest.RequestMatcher({
url: { pathSuffix: file }
})
],
actions: actions
})
}
prevFiles[sender.tab.id] = files
chrome.declarativeWebRequest.onRequest.addRules(rules, function (callback) {
// We reply back only when new rules are set.
sendResponse({})
})
}
// Return nothing to let the connection be cleaned up.
}
|
javascript
|
{
"resource": ""
}
|
q6913
|
waitFor
|
train
|
function waitFor (event, listener, context, wait) {
var timeout;
if (!wait) {
throw new Error("[FATAL] waitFor called without wait time");
}
var handler = function () {
clearTimeout(timeout);
listener.apply(context, arguments);
};
timeout = setTimeout(function () {
this.off(event, handler, context);
listener.call(context, "timeout");
}.bind(this), wait);
this.once(event, handler, context);
}
|
javascript
|
{
"resource": ""
}
|
q6914
|
listenFor
|
train
|
function listenFor (event, listener, context, duration) {
setTimeout(function () {
this.off(event, listener, context);
}.bind(this), duration);
this.on(event, listener, context);
}
|
javascript
|
{
"resource": ""
}
|
q6915
|
connectTo
|
train
|
function connectTo (connectionSettings, createCollections) {
const sequelize = new Sequelize(connectionSettings)
const collections = createCollections(sequelize, createCollection)
const database = {
/** @property {Sequelize} connection */
connection: sequelize,
/** @property {Object} collections { [name: string]: Collection } */
collections: collectionsAsKeyValue(collections),
applyChangeset (changeset, options) {
options = options || { transaction: null }
return changeset.apply(options.transaction)
},
createEventId () {
return uuid.v4()
},
transaction (callback) {
return sequelize.transaction((sequelizeTransaction) => {
const transaction = createTransaction(database, sequelizeTransaction)
return callback(transaction)
})
}
}
return sequelize.sync().then(() => database)
}
|
javascript
|
{
"resource": ""
}
|
q6916
|
stringifyObject
|
train
|
function stringifyObject(obj, prefix) {
var ret = []
, keys = objectKeys(obj)
, key;
for (var i = 0, len = keys.length; i < len; ++i) {
key = keys[i];
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
}
return ret.join('&');
}
|
javascript
|
{
"resource": ""
}
|
q6917
|
train
|
function(target, obj){
for (var attr in obj) {
if(obj.hasOwnProperty(attr)){
target[attr] = obj[attr];
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q6918
|
getCredits
|
train
|
function getCredits(projectPath, credits) {
credits = credits || [];
const jspmPath = path.join(projectPath, 'jspm_packages');
globby.sync([`${jspmPath}/npm/*/package.json`, `${jspmPath}/github/*/*/{package.json,bower.json}`])
.forEach(packagePath => {
if (path.basename(packagePath) === 'bower.json') {
return getBowerCredits(packagePath, credits);
}
return getNpmCredits(packagePath, credits);
});
return credits;
}
|
javascript
|
{
"resource": ""
}
|
q6919
|
getCredit
|
train
|
function getCredit(credits, author) {
const credit = credits.filter(credit => {
// Fallback to name when no email
// is available
if (credit.email && author.email) {
return credit.email === author.email;
}
return credit.name === author.name;
});
return credit.length > 0 ?
credit[0] :
false;
}
|
javascript
|
{
"resource": ""
}
|
q6920
|
addCreditToCredits
|
train
|
function addCreditToCredits(credits, person, name) {
let credit = getCredit(credits, person);
if (!credit) {
credit = person;
credit.packages = [];
credits.push(credit);
}
if (credit.packages.indexOf(name) === -1) {
credit.packages.push(name);
}
return credits;
}
|
javascript
|
{
"resource": ""
}
|
q6921
|
RedisStore
|
train
|
function RedisStore(port, host, options) {
port = port || 6379;
host = host || '127.0.0.1';
this._options = options || {};
this._options.redisstore = this._options.redisstore || {};
if(this._options.redisstore.database && !isNumber(this._options.redisstore.database)) {
throw new Error('database has to be a number (if provided at all)');
} else if(this._options.redisstore.database) {
this._database = this._options.redisstore.database;
} else {
this._database = 0;
}
this._tokenKey = this._options.redisstore.tokenkey || 'pwdless:';
delete this._options.redisstore;
this._client = redis.createClient(port, host, this._options);
}
|
javascript
|
{
"resource": ""
}
|
q6922
|
createOAuthWrapper
|
train
|
function createOAuthWrapper(oauthkey,
oauthsecret, headers) {
return new OAuthClient(
'https://api.7digital.com/1.2/oauth/requesttoken',
accessTokenUrl,
oauthkey, oauthsecret, '1.0', null, 'HMAC-SHA1', 32, headers);
}
|
javascript
|
{
"resource": ""
}
|
q6923
|
breadcrumb
|
train
|
function breadcrumb() {
const $breadcrumb = $(`.${namespace}-breadcrumbs`).empty();
chain().each(function () {
const $crumb = $(this);
$(`<span class="${namespace}-breadcrumb">`).text($crumb.text().trim()).click(function () {
$crumb.click();
}).appendTo($breadcrumb);
});
}
|
javascript
|
{
"resource": ""
}
|
q6924
|
animation
|
train
|
function animation($column, $columns) {
let width = 0;
chain().not($column).each(function () {
width += $(this).outerWidth(true);
});
$columns.stop().animate({
scrollLeft: width
}, settings.delay, function () {
const last = $columns.find(`.${namespace}-column:not(.${namespace}-collapse)`).last();
// last[0].scrollIntoView(); // Scrolls vertically also unfortunately
last[0].scrollLeft = width;
if (settings.scroll) {
settings.scroll.call(this, $column, $columns);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q6925
|
unnest
|
train
|
function unnest($columns) {
const queue = [];
let $node;
// Push the root unordered list item into the queue.
queue.push($columns.children());
while (queue.length) {
$node = queue.shift();
$node.children(itemSelector).each(function (item, el) {
const $this = $(this);
const $child = $this.children(columnSelector),
$ancestor = $this.parent().parent();
// Retain item hierarchy (because it is lost after flattening).
if ($ancestor.length && $this.data(`${namespace}-ancestor`) == null) {
// Use addBack to reset all selection chains.
$(this).siblings().addBack().data(`${namespace}-ancestor`, $ancestor);
}
if ($child.length) {
queue.push($child);
$(this).data(`${namespace}-child`, $child).addClass(`${namespace}-parent`);
}
// Causes item siblings to have a flattened DOM lineage.
$(this).parent(columnSelector).appendTo($columns).addClass(`${namespace}-column`);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q6926
|
getAllStar
|
train
|
function getAllStar(person) {
// Override properties from all-stars if available
const allStar = allStars(person);
return allStar ? objectAssign(person, allStar.subset()) : person;
}
|
javascript
|
{
"resource": ""
}
|
q6927
|
getPersonObject
|
train
|
function getPersonObject(personString) {
const regex = personString.match(/^(.*?)\s?(<(.*)>)?\s?(\((.*)\))?\s?$/);
return getAllStar({
name: regex[1],
email: regex[3],
url: regex[5]
});
}
|
javascript
|
{
"resource": ""
}
|
q6928
|
getAuthor
|
train
|
function getAuthor(packageJson) {
if (Array.isArray(packageJson.authors)) {
packageJson.authors = packageJson.authors.map(author => {
if (typeof author === 'string') {
return getPersonObject(author);
}
return getAllStar(author);
});
return packageJson.authors ? packageJson.authors : false;
}
if (typeof packageJson.author === 'string') {
return getPersonObject(packageJson.author);
}
return packageJson.author ?
getAllStar(packageJson.author) :
false;
}
|
javascript
|
{
"resource": ""
}
|
q6929
|
getMaintainers
|
train
|
function getMaintainers(packageJson) {
if (Array.isArray(packageJson.maintainers)) {
packageJson.maintainers = packageJson.maintainers.map(maintainer => {
if (typeof maintainer === 'string') {
return getPersonObject(maintainer);
}
return getAllStar(maintainer);
});
}
// Safety fix for people doing
// -> "maintainers" : "Bob <some.email>"
if (typeof packageJson.maintainers === 'string') {
packageJson.maintainers = [getPersonObject(packageJson.maintainers)];
}
return packageJson.maintainers ?
packageJson.maintainers :
false;
}
|
javascript
|
{
"resource": ""
}
|
q6930
|
getNpmCredits
|
train
|
function getNpmCredits(packagePath, credits) {
const directoryPath = path.dirname(packagePath);
const name = path.basename(path.dirname(packagePath));
if (
name[0] !== '.' && (
fs.lstatSync(directoryPath).isDirectory() ||
fs.lstatSync(directoryPath).isSymbolicLink()
)
) {
const packageJson = packageUtil.readJSONSync(packagePath);
const author = packageUtil.getAuthor(packageJson);
const maintainers = packageUtil.getMaintainers(packageJson);
if (author) {
credits = creditUtil.addCreditToCredits(credits, author, name);
}
if (maintainers) {
maintainers.forEach(maintainer => {
credits = creditUtil.addCreditToCredits(credits, maintainer, name);
});
}
}
return credits;
}
|
javascript
|
{
"resource": ""
}
|
q6931
|
getCredits
|
train
|
function getCredits(projectPath, credits) {
credits = credits || [];
const depPath = path.join(projectPath, 'node_modules');
globby.sync(`${depPath}/**/package.json`)
.forEach(packagePath => {
getNpmCredits(packagePath, credits);
});
return credits;
}
|
javascript
|
{
"resource": ""
}
|
q6932
|
preProcessBindings
|
train
|
function preProcessBindings(bindingString) {
var results = [];
var bindingHandlers = this.bindingHandlers;
var preprocessed;
// Check for a Provider.preprocessNode property
if (typeof this.preprocessNode === 'function') {
preprocessed = this.preprocessNode(bindingString, this);
if (preprocessed) { bindingString = preprocessed; }
}
for (var i = 0, j = this.bindingPreProcessors.length; i < j; ++i) {
preprocessed = this.bindingPreProcessors[i](bindingString, this);
if (preprocessed) { bindingString = preprocessed; }
}
function addBinding(name, value) {
results.push("'" + name + "':" + value);
}
function processBinding(key, value) {
// Get the "on" binding from "on.click"
var handler = bindingHandlers.get(key.split('.')[0]);
if (handler && typeof handler.preprocess === 'function') {
value = handler.preprocess(value, key, processBinding);
}
addBinding(key, value);
}
arrayForEach(parseObjectLiteral(bindingString), function(keyValueItem) {
processBinding(
keyValueItem.key || keyValueItem.unknown,
keyValueItem.value
);
});
return results.join(',');
}
|
javascript
|
{
"resource": ""
}
|
q6933
|
template
|
train
|
function template(url, params) {
var templated = url;
var keys = _.keys(params);
var loweredKeys = _.map(keys, function (key) {
return key.toLowerCase();
});
var keyLookup = _.zipObject(loweredKeys, keys);
_.each(templateParams(url), function replaceParam(param) {
var normalisedParam = param.toLowerCase().substr(1);
if (!keyLookup[normalisedParam]) {
throw new Error('Missing ' + normalisedParam);
}
templated = templated.replace(param,
params[keyLookup[normalisedParam]]);
delete params[keyLookup[normalisedParam]];
});
return templated;
}
|
javascript
|
{
"resource": ""
}
|
q6934
|
readDirectory
|
train
|
function readDirectory( projectPath, analyzers ) {
var credits = {};
for ( var analyzer in analyzers ) {
credits[ analyzer ] = analyzers[ analyzer ]( projectPath );
};
return credits;
}
|
javascript
|
{
"resource": ""
}
|
q6935
|
getBowerCredits
|
train
|
function getBowerCredits(bowerJsonPath, credits) {
const name = path.basename(path.dirname(bowerJsonPath));
const bowerJson = packageUtil.readJSONSync(bowerJsonPath);
const authors = packageUtil.getAuthor(bowerJson);
if (authors) {
authors.forEach(author => {
credits = creditUtil.addCreditToCredits(credits, author, name);
});
}
return credits;
}
|
javascript
|
{
"resource": ""
}
|
q6936
|
getCredits
|
train
|
function getCredits(projectPath, credits) {
credits = credits || [];
const depPath = path.join(projectPath, 'bower_components');
globby.sync([`${depPath}/*/bower.json`])
.forEach(bowerJsonPath => {
getBowerCredits(bowerJsonPath, credits);
});
return credits;
}
|
javascript
|
{
"resource": ""
}
|
q6937
|
arrySignaturesMatch
|
train
|
function arrySignaturesMatch(array1, array2){
// setup variables
var ref, test;
// we want to use the shorter array if one is longer
if (array1.length >= array2.length) {
ref = array2;
test = array1;
} else {
ref = array1;
test = array2;
}
// loop over the shorter array and make sure the corresponding key in the longer array matches
for(var key in ref) {
if(typeof ref[key] === typeof test[key]) {
// if the keys represent an object make sure that it matches
if(typeof ref[key] === "object" && typeof test[key] === "object") {
if(!objectSignaturesMatch(ref[key], test[key])){
return false;
}
}
// if the keys represent an array make sure that it matches
if(typeof ref[key] === "array" && typeof test[key] === "array") {
if(!arrySignaturesMatch(ref[key],test[key])){
return false;
}
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q6938
|
objectSignaturesMatch
|
train
|
function objectSignaturesMatch(object1, object2){
// because typeof null is object we need to check for it here before Object.keys
if(object1 === null && object2 === null){
return true;
}
// if the objects have different lengths of keys we should fail immediatly
if (Object.keys(object1).length !== Object.keys(object2).length) {
return false;
}
// loop over all the keys in object1 (we know the objects have the same number of keys at this point)
for(var key in object1) {
// if the keys match keep checking if not we have a mismatch
if(typeof object1[key] === typeof object2[key]) {
if(typeof object1[key] === null && typeof object2[key] === null) {
}
// if the keys represent an object make sure that it matches.
else if(object1[key] instanceof Array && object2[key] instanceof Array) {
if(!arrySignaturesMatch(object1[key],object2[key])){
return false;
}
}
// if the keys represent an array make sure it matches
else if(typeof object1[key] === "object" && typeof object2[key] === "object") {
if(!objectSignaturesMatch(object1[key],object2[key])){
return false;
}
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q6939
|
train
|
function() {
var refArgs = Array.prototype.slice.call(arguments);
var calledArgs = this.actual.mostRecentCall.args;
var arg;
for(arg in refArgs){
var ref = refArgs[arg];
var test = calledArgs[arg];
// if the types of the objects dont match
if(typeof ref !== typeof test) {
return false;
// if ref and test are objects make then
} else if(typeof ref === "object" && typeof test === "object") {
if(!objectSignaturesMatch(ref, test)){
return false;
}
} else if(typeof ref === "array" && typeof test === "array") {
if(!arrySignaturesMatch(ref, test)){
return false;
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q6940
|
getAnalyzers
|
train
|
function getAnalyzers(config) {
const methods = {};
const basePath = config.filePaths.analyzers;
globby.sync(`${basePath}/*`)
.forEach(analyzer => {
const name = path.basename(analyzer);
methods[name] = require(analyzer);
});
return methods;
}
|
javascript
|
{
"resource": ""
}
|
q6941
|
prepare
|
train
|
function prepare(data, consumerkey) {
var prop;
data = data || {};
for (prop in data) {
if (data.hasOwnProperty(prop)) {
if (_.isDate(data[prop])) {
data[prop] = helpers.toYYYYMMDD(data[prop]);
}
}
}
data.oauth_consumer_key = consumerkey;
return data;
}
|
javascript
|
{
"resource": ""
}
|
q6942
|
logHeaders
|
train
|
function logHeaders(logger, headers) {
return _.each(_.keys(headers), function (key) {
logger.info(key + ': ' + headers[key]);
});
}
|
javascript
|
{
"resource": ""
}
|
q6943
|
get
|
train
|
function get(endpointInfo, requestData, headers, credentials, logger,
callback) {
var normalisedData = prepare(requestData, credentials.consumerkey);
var fullUrl = endpointInfo.url + '?' + qs.stringify(normalisedData);
var hostInfo = {
host: endpointInfo.host,
port: endpointInfo.port
};
// Decide whether to make an oauth signed request or not
if (endpointInfo.authtype) {
hostInfo.host = endpointInfo.sslHost;
dispatchSecure(endpointInfo.url, 'GET', requestData, headers,
endpointInfo.authtype, hostInfo, credentials, logger,
callback);
} else {
dispatch(endpointInfo.url, 'GET', requestData, headers, hostInfo,
credentials, logger, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q6944
|
dispatchSecure
|
train
|
function dispatchSecure(path, httpMethod, requestData, headers, authtype,
hostInfo, credentials, logger, callback) {
var url;
var is2Legged = authtype === '2-legged';
var token = is2Legged ? null : requestData.accesstoken;
var secret = is2Legged ? null : requestData.accesssecret;
var mergedHeaders = createHeaders(hostInfo.host, headers);
var oauthClient = oauthHelper.createOAuthWrapper(credentials.consumerkey,
credentials.consumersecret, mergedHeaders);
var methodLookup = {
'POST' : oauthClient.post.bind(oauthClient),
'PUT' : oauthClient.put.bind(oauthClient)
};
var oauthMethod = methodLookup[httpMethod];
hostInfo.port = hostInfo.port || 443;
requestData = prepare(requestData, credentials.consumerkey);
if (!is2Legged) {
delete requestData.accesstoken;
delete requestData.accesssecret;
}
url = buildSecureUrl(httpMethod, hostInfo, path, requestData);
logger.info('token: ' + token + ' secret: ' + secret);
logger.info(httpMethod + ': ' + url + ' (' + authtype + ' oauth)');
logHeaders(logger, mergedHeaders);
function cbWithDataAndResponse(err, data, response) {
var apiError;
if (err) {
// API server error
if (err.statusCode && err.statusCode >= 400) {
// non 200 status and string for response body is usually an
// oauth error from one of the endpoints
if (typeof err.data === 'string' && /oauth/i.test(err.data)) {
apiError = new OAuthError(err.data, err.data + ': ' +
path);
} else {
apiError = new ApiHttpError(
response.statusCode, err.data, path);
}
return callback(apiError);
}
// Something unknown went wrong
logger.error(err);
return callback(err);
}
return callback(null, data, response);
}
if (httpMethod === 'GET') {
return oauthClient.get(url, token, secret, cbWithDataAndResponse);
}
if ( oauthMethod ) {
logger.info('DATA: ' + qs.stringify(requestData));
return oauthMethod(url, token, secret, requestData,
'application/x-www-form-urlencoded', cbWithDataAndResponse);
}
return callback(new Error('Unsupported HTTP verb: ' + httpMethod));
}
|
javascript
|
{
"resource": ""
}
|
q6945
|
dispatch
|
train
|
function dispatch(url, httpMethod, data, headers, hostInfo, credentials,
logger, callback) {
hostInfo.port = hostInfo.port || 80;
var apiRequest, prop, hasErrored;
var mergedHeaders = createHeaders(hostInfo.host, headers);
var apiPath = url;
data = prepare(data, credentials.consumerkey);
// Special case for track previews: we explicitly request to be given
// the XML response back instead of a redirect to the track download.
if (url.indexOf('track/preview') >= 0) {
data.redirect = 'false';
}
if (httpMethod === 'GET') {
url = url + '?' + qs.stringify(data);
}
logger.info(util.format('%s: http://%s:%s%s', httpMethod,
hostInfo.host, hostInfo.port, url));
logHeaders(logger, mergedHeaders);
// Make the request
apiRequest = http.request({
method: httpMethod,
hostname: hostInfo.host,
// Force scheme to http for browserify otherwise it will pick up the
// scheme from window.location.protocol which is app:// in firefoxos
scheme: 'http',
// Set this so browserify doesn't set it to true on the xhr, which
// causes an http status of 0 and empty response text as it forces
// the XHR to do a pre-flight access-control check and the API
// currently does not set CORS headers.
withCredentials: false,
path: url,
port: hostInfo.port,
headers: mergedHeaders
}, function handleResponse(response) {
var responseBuffer = '';
if (typeof response.setEncoding === 'function') {
response.setEncoding('utf8');
}
response.on('data', function bufferData(chunk) {
responseBuffer += chunk;
});
response.on('end', function endResponse() {
if (+response.statusCode >= 400) {
return callback(new ApiHttpError(
response.statusCode, responseBuffer, apiPath));
}
if (!hasErrored) {
return callback(null, responseBuffer, response);
}
});
});
apiRequest.on('error', function logErrorAndCallback(err) {
// Flag that we've errored so we don't call the callback twice
// if we get an end event on the response.
hasErrored = true;
logger.info('Error fetching [' + url + ']. Body:\n' + err);
return callback(new RequestError(err, url));
});
if (httpMethod === 'GET') {
apiRequest.end();
} else {
apiRequest.end(data);
}
}
|
javascript
|
{
"resource": ""
}
|
q6946
|
makeLogger
|
train
|
function makeLogger(level, method) {
// The logger function to return takes a variable number of arguments
// and formats like console.log
function logger() {
var args = [].slice.call(arguments);
var format = level.toUpperCase() + ': (api-client) ' + args.shift();
var logArgs = [format].concat(args);
return console[method].apply(console, logArgs);
}
return (level === 'warn' || level === 'error' || level === 'info')
? logger
: function() {};
}
|
javascript
|
{
"resource": ""
}
|
q6947
|
ensureCollections
|
train
|
function ensureCollections(collectionPaths, response) {
var basket;
_.each(collectionPaths, function checkLength(item) {
var parts = item.split('.');
var allPartsButLast = _.initial(parts);
var lastPart = _.last(parts);
var parents = _.reduce(allPartsButLast, function (chain, part) {
return chain.pluck(part).compact().flatten();
}, _([response])).value();
parents.map(function (parent) {
if (parent[lastPart]) {
parent[lastPart] = arrayify(parent[lastPart]);
} else {
parent[lastPart] = [];
}
});
});
basket = response.basket;
if (basket) {
if (basket.basketItems.basketItem) {
basket.basketItems = basket.basketItems.basketItem;
} else {
basket.basketItems = [];
}
}
return response;
}
|
javascript
|
{
"resource": ""
}
|
q6948
|
Api
|
train
|
function Api(options, schema) {
var prop, resourceOptions, resourceConstructor;
var apiRoot = this;
// Set default options for any unsupplied overrides
_.defaults(options, config);
this.options = options;
this.schema = schema;
configureSchemaFromEnv(this.schema);
// Creates a constructor with the pre-built resource as its prototype
// this is syntactic sugar to allow callers to new up the resources.
function createResourceConstructor(resourcePrototype) {
function APIResource(resourceOptions) {
// Allow creating resources without `new` keyword
if (!(this instanceof APIResource)) {
return new APIResource(resourceOptions);
}
resourceOptions = resourceOptions || {};
// Override any default options for all requests on this resource
_.defaults(resourceOptions.defaultParams,
apiRoot.options.defaultParams);
_.defaults(resourceOptions.headers,
apiRoot.options.headers);
_.defaults(resourceOptions, apiRoot.options);
this.format = resourceOptions.format;
this.logger = resourceOptions.logger;
this.defaultParams = resourceOptions.defaultParams;
this.headers = resourceOptions.headers;
}
APIResource.prototype = resourcePrototype;
return APIResource;
}
for (prop in schema.resources) {
if (schema.resources.hasOwnProperty(prop)) {
resourceOptions = options;
resourceOptions.api = this;
resourceOptions.resourceDefinition =
schema.resources[prop];
this[prop] = createResourceConstructor(
new Resource(resourceOptions, schema));
}
}
this['OAuth'] = createResourceConstructor(new OAuth(options));
}
|
javascript
|
{
"resource": ""
}
|
q6949
|
createResourceConstructor
|
train
|
function createResourceConstructor(resourcePrototype) {
function APIResource(resourceOptions) {
// Allow creating resources without `new` keyword
if (!(this instanceof APIResource)) {
return new APIResource(resourceOptions);
}
resourceOptions = resourceOptions || {};
// Override any default options for all requests on this resource
_.defaults(resourceOptions.defaultParams,
apiRoot.options.defaultParams);
_.defaults(resourceOptions.headers,
apiRoot.options.headers);
_.defaults(resourceOptions, apiRoot.options);
this.format = resourceOptions.format;
this.logger = resourceOptions.logger;
this.defaultParams = resourceOptions.defaultParams;
this.headers = resourceOptions.headers;
}
APIResource.prototype = resourcePrototype;
return APIResource;
}
|
javascript
|
{
"resource": ""
}
|
q6950
|
_getIdByUsername
|
train
|
function _getIdByUsername(username) {
const url = `${API}/get-user-id`;
const params = {
app: 3,
username
};
return http
.GET(url, params)
.then(data => data.user_id);
}
|
javascript
|
{
"resource": ""
}
|
q6951
|
rant
|
train
|
function rant(id = _noRantIdError()) {
const url = `${API}/devrant/rants/${id}`;
const params = { app: 3 };
return http.GET(url, params);
}
|
javascript
|
{
"resource": ""
}
|
q6952
|
rants
|
train
|
function rants({
sort = 'algo',
limit = 50,
skip = 0
} = {}) {
const url = `${API}/devrant/rants`;
const params = {
app: 3,
sort, limit, skip
};
return http
.GET(url, params)
.then(data => data.rants);
}
|
javascript
|
{
"resource": ""
}
|
q6953
|
search
|
train
|
function search(term = _noSearchTermError()) {
const url = `${API}/devrant/search`;
const params = {
app: 3,
term
};
return http
.GET(url, params)
.then(data => data.results);
}
|
javascript
|
{
"resource": ""
}
|
q6954
|
profile
|
train
|
function profile(username = _noUsernameError()) {
return co(function *resolveUsername() {
const userId = yield _getIdByUsername(username);
const url = `${API}/users/${userId}`;
const params = { app: 3 };
return http
.GET(url, params)
.then(data => data.profile);
});
}
|
javascript
|
{
"resource": ""
}
|
q6955
|
to2
|
train
|
function to2 (alpha3) {
if (alpha3 && alpha3.length > 1) state = alpha3
if (state.length !== 3) return state
return ISOCodes.filter(function (row) {
return row.alpha3 === state
})[0].alpha2
}
|
javascript
|
{
"resource": ""
}
|
q6956
|
to3
|
train
|
function to3 (alpha2) {
if (alpha2 && alpha2.length > 1) state = alpha2
if (state.length !== 2) return state
return ISOCodes.filter(function (row) {
return row.alpha2 === state
})[0].alpha3
}
|
javascript
|
{
"resource": ""
}
|
q6957
|
Resource
|
train
|
function Resource(options, schema) {
this.logger = options.logger;
this.resourceName = options.resourceDefinition.resource;
this.host = options.resourceDefinition.host || schema.host;
this.sslHost = options.resourceDefinition.sslHost || schema.sslHost;
this.port = options.resourceDefinition.port || schema.port;
this.prefix = options.resourceDefinition.prefix || schema.prefix;
this.consumerkey = options.consumerkey;
this.consumersecret = options.consumersecret;
if(this.logger.silly) {
this.logger.silly('Creating constructor for resource: ' + this.resourceName);
}
_.each(options.resourceDefinition.actions,
function processAction(action) {
this.createAction(action, options.userManagement);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q6958
|
truncFilename
|
train
|
function truncFilename(path, rootFolderName) {
// bail if a string wasn't provided
if (typeof path !== 'string') {
return path;
}
var index = path.indexOf(rootFolderName);
if (index > 0) {
return path.substring(index + rootFolderName.length + 1);
} else {
return path;
}
}
|
javascript
|
{
"resource": ""
}
|
q6959
|
getTimestampString
|
train
|
function getTimestampString(date) {
// all this nasty code is faster (~30k ops/sec) than doing "moment(date).format('HH:mm:ss:SSS')" and means 0 dependencies
var hour = '0' + date.getHours();
hour = hour.slice(hour.length - 2);
var minute = '0' + date.getMinutes();
minute = minute.slice(minute.length - 2);
var second = '0' + date.getSeconds();
second = second.slice(second.length - 2);
var ms = '' + date.getMilliseconds();
// https://github.com/MarkHerhold/palin/issues/6
// this is faster than using an actual left-pad algorithm
if (ms.length === 1) {
ms = '00' + ms;
} else if (ms.length === 2) {
ms = '0' + ms;
} // no modifications for 3 or more digits
return chalk.dim(`${hour}:${minute}:${second}:${ms}`);
}
|
javascript
|
{
"resource": ""
}
|
q6960
|
getColorSeverity
|
train
|
function getColorSeverity(severity) {
// get the color associated with the severity level
const color = severityMap[severity] || 'white';
return chalk[color].bold(severity.toUpperCase());
}
|
javascript
|
{
"resource": ""
}
|
q6961
|
formatter
|
train
|
function formatter(options, severity, date, elems) {
/*
OPTIONS
*/
const indent = options.indent || defaultIndent;
const objectDepth = options.objectDepth;
const timestamp = (function () {
if (check.function(options.timestamp)) {
return options.timestamp; // user-provided timestamp generating function
} else if (options.timestamp === false) {
return false; // no timestamp
} else {
return getTimestampString; // default timestamp generating function
}
})();
const rootFolderName = options.rootFolderName;
/*
LOGIC
*/
// the last element is an aggregate object of all of the additional passed in elements
var aggObj = elems[elems.length - 1];
// initial log string
var build = ' ';
// add the date
if (timestamp !== false) {
// otherwise, use the default timestamp generator function
build += ' ' + timestamp(date);
}
build += ' ' + getColorSeverity(severity) + ' ';
// add the component if provided
if (aggObj.scope) {
build += getScopeString(aggObj.scope) + ' ';
delete aggObj.scope;
}
// errors are a special case that we absolutely need to keep track of and log the entire stack
var errors = [];
for (let i = 0; i < elems.length - 1; i++) { // iterate through all elements in the array except the last (obj map of options)
let element = elems[i];
// Attempt to determine an appropriate title given the first element
if (i === 0) {
let elementConsumed = false;
if (check.string(element)) {
// string is obviously the title
build += chalk.blue(element);
elementConsumed = true;
} else if (check.instance(element, Error)) {
// title is the error text representation
build += chalk.blue(element.message || '[no message]');
// also store error stacktrace in the aggregate object
errors.push(element);
elementConsumed = true;
}
// add on the file and line number, which always go after the title, inline
if (aggObj.file && aggObj.line) {
aggObj.file = truncFilename(aggObj.file, rootFolderName);
build += chalk.dim(` (${aggObj.file}:${aggObj.line})`);
delete aggObj.file;
delete aggObj.line;
}
// do not add element 0 to the 'extra' data section
if (elementConsumed) {
continue;
}
}
// add the element to the errors array if it's an error
if (check.instance(element, Error)) {
errors.push(element);
// the error will be concatinated later so continue to the next element
continue;
}
let objString = '\n' + util.inspect(element, { colors: true, depth: objectDepth });
build += objString.replace(/\n/g, indent);
}
if (Object.keys(aggObj).length > 0) {
let objString = '\n' + util.inspect(aggObj, { colors: true, depth: objectDepth });
build += objString.replace(/\n/g, indent);
}
// iterate through the top-level object keys looking for Errors as well
for (let o of Object.keys(aggObj)) {
if (check.instance(o, Error)) {
errors.push(o);
}
}
// iterate through all the Error objects and print the stacks
for (let e of errors) {
build += indent + e.stack.replace(/\n/g, indent);
}
return build;
}
|
javascript
|
{
"resource": ""
}
|
q6962
|
parse
|
train
|
function parse(response, opts, callback) {
var parser, jsonParseError, result;
if (opts.format.toUpperCase() === 'XML') {
callback(null, response);
return;
}
if (opts.contentType && opts.contentType.indexOf('json') >= 0) {
try {
result = JSON.parse(response);
} catch (e) {
jsonParseError = e;
}
return validateAndCleanResponse(jsonParseError, { response: result });
}
parser = new xml2js.Parser({
mergeAttrs: true,
explicitArray: false
});
parser.parseString(response, validateAndCleanResponse);
function validateAndCleanResponse(err, result) {
var cleanedResult;
var clean, error, apiError;
function makeParseErr(msg) {
return new ApiParseError(msg + ' from: ' + opts.url, response);
}
// Unparsable response text
if (err) {
return callback(makeParseErr('Unparsable api response'));
}
if (!result) {
return callback(makeParseErr('Empty response'));
}
if (!result.response) {
return callback(makeParseErr('Missing response node'));
}
// Reponse was a 7digital API error object
if (result.response.status === 'error') {
error = result.response.error;
if (/oauth/i.test(error.errorMessage)) {
return callback(new OAuthError(error,
error.errorMessage + ': ' + opts.url));
}
apiError = new ApiError(error, error.errorMessage + ': '
+ opts.url);
apiError.params = opts.params;
return callback(apiError);
} else if (result.response.status !== 'ok') {
return callback(new ApiParseError(
'Unexpected response status from: ' + opts.url, response));
}
clean = _.compose(
cleaners.renameCardTypes,
cleaners.ensureCollections.bind(null, cleaners.collectionPaths),
cleaners.removeXmlNamespaceKeys,
cleaners.nullifyNils);
cleanedResult = clean(result.response);
return callback(null, cleanedResult);
}
}
|
javascript
|
{
"resource": ""
}
|
q6963
|
ApiHttpError
|
train
|
function ApiHttpError(statusCode, response, message) {
this.name = "ApiHttpError";
this.statusCode = statusCode;
this.response = response;
this.message = message || response
|| util.format('Unexpected %s status code', statusCode);
if (Error.captureStackTrace
&& typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ApiHttpError);
}
}
|
javascript
|
{
"resource": ""
}
|
q6964
|
ApiParseError
|
train
|
function ApiParseError(parseErrorMessage, response) {
this.name = "ApiParseError";
this.response = response;
this.message = parseErrorMessage;
if (Error.captureStackTrace
&& typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ApiParseError);
}
}
|
javascript
|
{
"resource": ""
}
|
q6965
|
RequestError
|
train
|
function RequestError(err, url) {
VError.call(this, err, 'for url %s', url);
this.name = RequestError.name;
}
|
javascript
|
{
"resource": ""
}
|
q6966
|
OAuthError
|
train
|
function OAuthError(errorResponse, message) {
this.name = "OAuthError";
this.message = message || errorResponse.errorMessage;
this.code = errorResponse.code;
this.response = errorResponse;
if (Error.captureStackTrace
&& typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, OAuthError);
}
}
|
javascript
|
{
"resource": ""
}
|
q6967
|
train
|
function(args, data, msg) {
if (typeof (args) !== 'object') {
args = [args];
}
for (var i in args) {
if (args.hasOwnProperty(i) === false) continue;
if (JOII.Compat.indexOf(data, args[i]) !== -1) {
throw msg;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6968
|
parseLinkHeader
|
train
|
function parseLinkHeader(header) {
if (!header) {
return {};
}
// Split parts by comma
const parts = header.split(',');
const links = {};
// Parse each part into a named link
parts.forEach((p) => {
const section = p.split(';');
if (section.length != 2) {
throw new Error('section could not be split on ";"');
}
const url = section[0].replace(/<(.*)>/, '$1').trim();
const name = section[1].replace(/rel="(.*)"/, '$1').trim();
links[name] = url;
});
return links;
}
|
javascript
|
{
"resource": ""
}
|
q6969
|
train
|
function (name) {
if (JOII.Config.constructors.indexOf(name) !== -1) {
return;
}
JOII.Config.constructors.push(name);
}
|
javascript
|
{
"resource": ""
}
|
|
q6970
|
train
|
function(name) {
if (JOII.Config.constructors.indexOf(name) === -1) {
return;
}
JOII.Config.constructors.splice(JOII.Config.constructors.indexOf(name), 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q6971
|
train
|
function(msg) {
if (yahoo.logging) {
console.log('ERROR: ' + msg);
}
if (module.exports.error) {
module.exports.error(msg);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6972
|
processNewMessage
|
train
|
function processNewMessage(msg, mailMessage) {
// msg = JSON.parse(JSON.stringify(msg)); // Clone the message
// Populate the msg fields from the content of the email message
// that we have just parsed.
msg.payload = mailMessage.text;
msg.topic = mailMessage.subject;
msg.date = mailMessage.date;
msg.header = mailMessage.headers;
if (mailMessage.html) {
msg.html = mailMessage.html;
}
if (mailMessage.to && mailMessage.from.to > 0) {
msg.to = mailMessage.to;
}
if (mailMessage.cc && mailMessage.from.cc > 0) {
msg.cc = mailMessage.cc;
}
if (mailMessage.bcc && mailMessage.from.bcc > 0) {
msg.bcc = mailMessage.bcc;
}
if (mailMessage.from && mailMessage.from.length > 0) {
msg.from = mailMessage.from[0].address;
}
if (mailMessage.attachments) {
msg.attachments = mailMessage.attachments;
} else {
msg.attachments = [];
}
n.send(msg); // Propagate the message down the flow
}
|
javascript
|
{
"resource": ""
}
|
q6973
|
checkPOP3
|
train
|
function checkPOP3(msg) {
let currentMessage;
let maxMessage;
// Form a new connection to our email server using POP3.
let pop3Client = new POP3Client(
node.port, node.server,
{enabletls: node.useSSL} // Should we use SSL to connect to our email server?
);
// If we have a next message to retrieve, ask to retrieve it otherwise issue a
/**
* If we have a next message to retrieve, ask to retrieve it otherwise issue a
*/
function nextMessage() {
if (currentMessage > maxMessage) {
pop3Client.quit();
return;
}
pop3Client.retr(currentMessage);
currentMessage++;
} // End of nextMessage
pop3Client.on('stat', function(status, data) {
// Data contains:
// {
// count: <Number of messages to be read>
// octect: <size of messages to be read>
// }
if (status) {
currentMessage = 1;
maxMessage = data.count;
nextMessage();
} else {
node.log(util.format('stat error: %s %j', status, data));
}
});
pop3Client.on('error', function(err) {
node.log('We caught an error: ' + JSON.stringify(err));
});
pop3Client.on('connect', function() {
// node.log("We are now connected");
pop3Client.login(node.userid, node.password);
});
pop3Client.on('login', function(status, rawData) {
// node.log("login: " + status + ", " + rawData);
if (status) {
pop3Client.stat();
} else {
node.log(util.format('login error: %s %j', status, rawData));
pop3Client.quit();
}
});
pop3Client.on('retr', function(status, msgNumber, data, rawData) {
// node.log(util.format("retr: status=%s, msgNumber=%d, data=%j", status, msgNumber, data));
if (status) {
// We have now received a new email message. Create an instance of a mail parser
// and pass in the email message. The parser will signal when it has parsed the message.
let mailparser = new MailParser();
mailparser.on('end', function(mailObject) {
// node.log(util.format("mailparser: on(end): %j", mailObject));
processNewMessage(msg, mailObject);
});
mailparser.write(data);
mailparser.end();
pop3Client.dele(msgNumber);
} else {
node.log(util.format('retr error: %s %j', status, rawData));
pop3Client.quit();
}
});
pop3Client.on('invalid-state', function(cmd) {
node.log('Invalid state: ' + cmd);
});
pop3Client.on('locked', function(cmd) {
node.log('We were locked: ' + cmd);
});
// When we have deleted the last processed message, we can move on to
// processing the next message.
pop3Client.on('dele', function(status, msgNumber) {
nextMessage();
});
}
|
javascript
|
{
"resource": ""
}
|
q6974
|
processValuesFromContext
|
train
|
function processValuesFromContext(node, params, msg, varList) {
let pMsg = {};
Object.assign(pMsg, params);
varList.forEach((varItem) => {
if (varItem.type === undefined || params[varItem.type] === undefined) {
pMsg[varItem.name] = params[varItem.name];
} else if (params[varItem.type] === 'flow' || params[varItem.type] === 'global') {
pMsg[varItem.name] = RED.util.evaluateNodeProperty(params[varItem.name], params[varItem.type], node, msg);
pMsg[varItem.type] = params[varItem.type];
console.log('Inside flow or global');
console.log(varItem.name + ' - - ' + pMsg[varItem.name]);
} else {
pMsg[varItem.name] = params[varItem.name];
pMsg[varItem.type] = params[varItem.type];
}
});
return pMsg;
}
|
javascript
|
{
"resource": ""
}
|
q6975
|
splitRow
|
train
|
function splitRow(s, delimiter) {
var row = [], c, col = '', i, inString = false;
s = s.trim();
for (i = 0; i < s.length; i += 1) {
c = s[i];
if (c === '"') {
if (s[i+1] === '"') {
col += '"';
i += 1;
} else {
inString = !inString;
}
} else if (c === delimiter) {
if (!inString) {
row.push(col);
col = '';
} else {
col += c;
}
} else {
col += c;
}
}
row.push(col);
return row;
}
|
javascript
|
{
"resource": ""
}
|
q6976
|
train
|
function(name) {
var list = this.getProperties();
for (var i in list) {
if (list[i].getName() === name) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q6977
|
train
|
function(filter) {
var result = [];
for (var i in this.proto) {
if (typeof (this.proto[i]) === 'function' && JOII.Compat.indexOf(JOII.InternalPropertyNames, i) === -1) {
result.push(new JOII.Reflection.Method(this, i));
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q6978
|
train
|
function(name) {
var list = this.getMethods();
for (var i in list) {
if (list[i].getName() === name) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q6979
|
train
|
function(name) {
var list = this.getMethods();
for (var i in list) {
if (list[i].getName() === name) {
return list[i];
}
}
throw 'Method "' + name + '" does not exist.';
}
|
javascript
|
{
"resource": ""
}
|
|
q6980
|
train
|
function(name) {
var list = this.getProperties();
for (var i in list) {
if (list[i].getName() === name) {
return list[i];
}
}
throw 'Property "' + name + '" does not exist.';
}
|
javascript
|
{
"resource": ""
}
|
|
q6981
|
train
|
function() {
var name_parts = [],
proto_ref = this.reflector.getProto()[this.name],
name = '',
body = '';
if (this.meta.is_abstract) { name_parts.push('abstract'); }
if (this.meta.is_final) { name_parts.push('final'); }
name_parts.push(this.meta.visibility);
if (this.meta.is_static) { name_parts.push('static'); }
if (this.meta.is_nullable) { name_parts.push('nullable'); }
if (this.meta.is_read_only) { name_parts.push('read'); }
// If type === null, attempt to detect it by the predefined value.
if (this.meta.type === null) {
if (proto_ref === null) {
name_parts.push('mixed');
} else {
name_parts.push(typeof (proto_ref));
}
} else {
name_parts.push(this.meta.type);
}
name_parts.push('"' + this.meta.name + '"');
name = name_parts.join(' ');
if (typeof (proto_ref) === 'function') {
body = '[Function]';
} else if (typeof (proto_ref) === 'object' && proto_ref !== null) {
body = '[Object (' + proto_ref.length + ')]';
} else if (typeof (proto_ref) === 'string') {
body = '"' + proto_ref + '"';
} else {
body = proto_ref;
}
return name + ': ' + body;
}
|
javascript
|
{
"resource": ""
}
|
|
q6982
|
train
|
function() {
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m,
FN_ARG_SPLIT = /,/,
FN_ARG = /^\s*(_?)(\S+?)\1\s*$/,
STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
getParams = function(fn) {
var fnText, argDecl;
var args = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
var r = argDecl[1].split(FN_ARG_SPLIT), repl = function(all, underscore, name) {
args.push(name);
};
for (var a in r) {
var arg = r[a];
arg.replace(FN_ARG, repl);
}
return args;
};
var prototype = this.reflector.getProto();
var overloads = prototype.__joii__.metadata[this.name].overloads;
if (!overloads || overloads.length === 0) {
// old method for BC (wasn't recognized as a function when prototyping)
return getParams(this.reflector.getProto()[this.name]);
} else if (overloads.length === 1 && overloads[0].parameters.length === 0) {
// old method for BC (was recognized when prototyping, but old style)
return getParams(overloads[0].fn);
}
else {
var ret = [];
for (var idx = 0; idx < overloads.length; idx++) {
var fn_meta = [];
var function_parameters_meta = overloads[idx];
var parsed_params = getParams(function_parameters_meta.fn);
for (var j = 0; j < function_parameters_meta.parameters.length; j++) {
var param = {
name: parsed_params.length > j ? parsed_params[j] : null,
type: function_parameters_meta.parameters[j]
};
fn_meta.push(param);
}
ret.push(fn_meta);
}
return ret;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6983
|
train
|
function(f) {
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
fn_text = this.reflector.getProto()[this.name].toString().replace(STRIP_COMMENTS, '');
return fn_text.substr(fn_text.indexOf('{') + 1, fn_text.lastIndexOf('}') - 4).replace(/}([^}]*)$/, '$1');
}
|
javascript
|
{
"resource": ""
}
|
|
q6984
|
train
|
function() {
// Get the "declaration" part of the method.
var prefix = this['super']('toString').split(':')[0],
body = '[Function',
args = this.getParameters(),
is_var = this.usesVariadicArguments();
if (args.length > 0 && typeof (args[0]) === 'object') {
// right now, this is spitting out every overload's signature one after another, each on a new line.
// should probably find a better way to do this
for (var idx = 0; idx < args.length; idx++) {
var function_parameters_meta = args[idx];
body += ' (';
var first_time = true;
for (var i = 0; i < function_parameters_meta.length; i++) {
if (!first_time) {
body += ', ';
}
first_time = false;
body += function_parameters_meta[i].type;
if (function_parameters_meta[i].name !== null) {
body += " " + function_parameters_meta[i].name;
is_var = true;
}
}
var data = this.reflector.getProto().__joii__.metadata[this.name].overloads[idx].fn.toString();
is_var = data.match(/[\(|\.|\ ](arguments)[\)|\.|\,|\ |]/g);
if (is_var) {
body += ', ...';
}
body += ')\n';
}
} else if (args.length > 0) {
body += ' (' + args.join(', ');
if (is_var) {
body += ', ...';
}
body += ')';
} else if (args.length === 0 && is_var) {
body += ' (...)';
}
body += ']';
return prefix + ': ' + body;
}
|
javascript
|
{
"resource": ""
}
|
|
q6985
|
sendError
|
train
|
function sendError(node, msg, err, ...attrs) {
if (check.string(err)) {
msg.error = {
node: node.name,
message: util.format(err, ...attrs),
};
} else if (check.instance(err, Error)) {
msg.error = err;
}
node.error(node.name + ': ' + msg.error.message, msg);
}
|
javascript
|
{
"resource": ""
}
|
q6986
|
Walk
|
train
|
function Walk(root, onDir, onEnd, onError) {
if (!(this instanceof Walk)) {
return new Walk(root, onDir, onEnd, onError);
}
this.dirs = [path.resolve(root)];
if (onDir) {
this.on('dir', onDir);
}
if (onEnd) {
this.on('end', onEnd);
}
onError && this.on('error', onError);
var self = this;
// let listen `files` Event first.
process.nextTick(function () {
self.next();
});
}
|
javascript
|
{
"resource": ""
}
|
q6987
|
LineReader
|
train
|
function LineReader(file) {
if (typeof file === 'string') {
this.readstream = fs.createReadStream(file);
} else {
this.readstream = file;
}
this.remainBuffers = [];
var self = this;
this.readstream.on('data', function (data) {
self.ondata(data);
});
this.readstream.on('error', function (err) {
self.emit('error', err);
});
this.readstream.on('end', function () {
self.emit('end');
});
}
|
javascript
|
{
"resource": ""
}
|
q6988
|
loadWebAssembly
|
train
|
function loadWebAssembly(filename, imports) {
// Fetch the file and compile it
return fetch(filename)
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.compile(buffer))
.then(module => {
// create the imports for the module, including the
// standard dynamic library imports
imports = imports || {};
imports.env = imports.env || {};
imports.env.memoryBase = imports.env.memoryBase || 0;
imports.env.tableBase = imports.env.tableBase || 0;
// note: just take really memory for now...
if (!imports.env.memory)
imports.env.memory = new WebAssembly.Memory({ initial: 256 });
if (!imports.env.table)
imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' });
// create the instance
const instance = new WebAssembly.Instance(module, imports);
return Promise.resolve({ instance, imports });
});
}
|
javascript
|
{
"resource": ""
}
|
q6989
|
train
|
function(message) {
if (debug) console.log('Decoding HEP3 Packet...');
try {
var HEP = hepHeader.parse(message);
if(HEP.payload && HEP.payload.length>0){
var data = HEP.payload;
var tot = 0;
var decoded = {};
var PAYLOAD;
while(true){
PAYLOAD = hepParse.parse( data.slice(tot) );
var tmp = hepDecode(PAYLOAD);
decoded = mixinDeep(decoded, tmp);
tot += PAYLOAD.length;
if(tot>=HEP.payload.length) { break; }
}
if(debug) console.log(decoded);
return decoded;
}
} catch(e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6990
|
toGradientData
|
train
|
function toGradientData(v1, v2, v3, v4, v5) {
var startColor, endColor, type, rotation, spread, d;
var data = {};
if (arguments.length === 1) { // The argument is a dictionary or undefined.
d = v1 || {};
startColor = d.startColor;
endColor = d.endColor;
type = d.type;
rotation = d.rotation;
spread = d.spread;
} else if (arguments.length >= 2) { // The first two arguments are a start color and an end color.
startColor = v1;
endColor = v2;
type = 'linear';
rotation = 0;
spread = 0;
if (arguments.length === 3) {
if (typeof v3 === 'string') { // The type can be either linear or radial.
type = v3;
} else if (typeof v3 === 'number') { // The type is implicitly linear and the third argument is the rotation angle.
rotation = v3;
}
} else if (arguments.length === 4) {
if (typeof v3 === 'number') { // The type is implicitly linear and the third/forth arguments are the rotation angle and gradient spread.
rotation = v3;
spread = v4;
} else if (v3 === 'linear') { // The type is explicitly linear and the forth argument is the rotation angle.
rotation = v4;
} else if (v3 === 'radial') { // The type is explicitly radial and the forth argument is the gradient spread.
type = v3;
spread = v4;
} else {
throw new Error('Wrong argument provided: ' + v3);
}
} else if (arguments.length === 5) { // Type, rotation (unused in case of radial type gradient), and gradient spread.
type = v3;
rotation = v4;
spread = v5;
}
}
if (!startColor && startColor !== 0) {
throw new Error('No startColor was given.');
}
if (!endColor && endColor !== 0) {
throw new Error('No endColor was given.');
}
try {
data.startColor = toColor(startColor);
} catch (e1) {
throw new Error('startColor is not a valid color: ' + startColor);
}
try {
data.endColor = toColor(endColor);
} catch (e2) {
throw new Error('endColor is not a valid color: ' + endColor);
}
if (type === undefined) {
type = 'linear';
}
if (type !== 'linear' && type !== 'radial') {
throw new Error('Unknown gradient type: ' + type);
}
data.type = type;
if (spread === undefined) {
spread = 0;
}
if (typeof spread !== 'number') {
throw new Error('Spread value is not a number: ' + spread);
}
if (type === 'linear') {
if (rotation === undefined) {
rotation = 0;
}
if (typeof rotation !== 'number') {
throw new Error('Rotation value is not a number: ' + rotation);
}
data.rotation = rotation;
}
data.spread = clamp(spread, 0, 0.99);
return data;
}
|
javascript
|
{
"resource": ""
}
|
q6991
|
train
|
function (canvas) {
this.width = canvas.width;
this.height = canvas.height;
var ctx = canvas.getContext('2d');
this._data = ctx.getImageData(0, 0, this.width, this.height);
this.array = this._data.data;
}
|
javascript
|
{
"resource": ""
}
|
|
q6992
|
walkModules
|
train
|
function walkModules(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = dir + path.sep + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
if (file.indexOf('node_modules') > -1) {
walkModules(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
}
else {
if (!--pending) done(null, results);
}
} else {
if (file.slice(-12) === 'package.json') {
var parts = file.split(path.sep);
if (parts[parts.length-3] === 'node_modules') {
results.push(file);
}
}
if (!--pending) done(null, results);
}
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q6993
|
readRows
|
train
|
function readRows(ws, rows, opts) {
let contents = {};
if (typeof rows === 'string') {
rows = rows.split(',');
}
opts = (opts === undefined) ? {} : opts;
// console.log('Typeof Rows %s', typeof rows);
// console.log('Typeof Rows %s', rows);
// console.log('Length Rows %d', rows.length);
let dRange = xlsx.utils.decode_range(ws['!ref']);
for (let i = 0; i < rows.length; ++i) {
// console.log('rows[%d]=%s', i, rows[i]);
let dRow = xlsx.utils.decode_row(rows[i]);
for (let C = dRange.s.c; C <= dRange.e.c; ++C) {
let encCell = xlsx.utils.encode_cell({c: C, r: dRow});
contents[encCell] = ws[encCell] || {};
}
}
contents['!ref'] = ws['!ref'];
if (opts.asis) {
return contents;
}
Object.assign(opts, {
header: 1,
raw: true,
blankrows: true,
});
opts.header = opts.useLabel ? 'A' : opts.header;
let contentsJson = xlsx.utils.sheet_to_json(contents, opts);
if (opts.removeEmpty) {
contentsJson = contentsJson.filter((row) => {
// console.log(typeof row);
return check.object(row) ?
check.nonEmptyObject(row) : check.nonEmptyArray(row);
});
}
return contentsJson;
}
|
javascript
|
{
"resource": ""
}
|
q6994
|
readCols
|
train
|
function readCols(ws, cols, opts) {
// console.log('Reading cols ' + cols.length);
// console.log(cols);
let contents = {};
if (typeof cols === 'string') {
cols = cols.split(',');
}
opts = (opts === undefined) ? {} : opts;
let dRange = xlsx.utils.decode_range(ws['!ref']);
for (let i = 0; i < cols.length; ++i) {
// console.log('Reading col:' + cols[i]);
let dCol = xlsx.utils.decode_col(cols[i]);
for (let R = dRange.s.r; R <= dRange.e.r; ++R) {
// console.log('Reading cell:' + cols[i] + ', ' + R);
let encCell = xlsx.utils.encode_cell({c: dCol, r: R});
contents[encCell] = ws[encCell] || {};
// console.log('Done cell:' + cols[i] + ', ' + R + ', ' + JSON.stringify(contents[encCell]));
}
}
contents['!ref'] = ws['!ref'];
if (opts.asis) {
return contents;
}
Object.assign(opts, {
header: 1,
raw: true,
blankrows: true,
});
opts.header = opts.useLabel ? 'A' : opts.header;
let contentsJson = xlsx.utils.sheet_to_json(contents, opts);
if (opts.removeEmpty) {
contentsJson = contentsJson.filter((col) => {
// console.log(typeof col);
return check.object(col) ? check.nonEmptyObject(col) : check.nonEmptyArray(col);
});
}
return contentsJson;
}
|
javascript
|
{
"resource": ""
}
|
q6995
|
readRegion
|
train
|
function readRegion(ws, range, opts) {
let contents = {};
opts = (opts === undefined) ? {} : opts;
// console.log('Xref:%s', ws['!ref']);
let dORange = xlsx.utils.decode_range(ws['!ref']);
let dRange = xlsx.utils.decode_range(range);
// Support for cols only ranges like !A:A,!A:C
dRange.s.r = (isNaN(dRange.s.r)) ? dORange.s.r : dRange.s.r;
dRange.e.r = (isNaN(dRange.e.r)) ? dORange.e.r : dRange.e.r;
// Single for row only ranges like !1:1, !1:3
dRange.s.c = (dRange.s.c === -1) ? dORange.s.c : dRange.s.c;
dRange.e.c = (dRange.e.c === -1) ? dORange.e.c : dRange.e.c;
for (let R = dRange.s.r; R <= dRange.e.r; ++R) {
for (let C = dRange.s.c; C <= dRange.e.c; ++C) {
let cellref = xlsx.utils.encode_cell({c: C, r: R});
contents[cellref] = ws[cellref] || {};
}
}
// console.log(JSON.stringify(dRange));
contents['!ref'] = xlsx.utils.encode_range(dRange);
if (opts.asis) {
return contents;
}
Object.assign(opts, {
header: 1,
raw: true,
blankrows: true,
});
opts.header = opts.useLabel ? 'A' : opts.header;
let contentsJson = xlsx.utils.sheet_to_json(contents, opts);
if (opts.removeEmpty) {
contentsJson = contentsJson.filter((row) => {
// console.log(typeof row);
return check.object(row) ?
check.nonEmptyObject(row) : check.nonEmptyArray(row);
});
}
return contentsJson;
}
|
javascript
|
{
"resource": ""
}
|
q6996
|
writeRegion
|
train
|
function writeRegion(ws, urange, contents) {
let range = ws['!ref'];
range = check.undefined(range) ? 'A1:A1' : range;
let dRange = xlsx.utils.decode_range(range);
let dUrange = xlsx.utils.decode_range(urange);
let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}};
let encCell;
for (let R = dUrange.s.r, i = 0; R <= dUrange.e.r; ++R, ++i) {
let cellVal = contents[i];
if (R > newRef.e.r) {
newRef.e.r = R;
}
for (let C = dUrange.s.c, j = 0; C <= dUrange.e.c; ++C, ++j) {
encCell = xlsx.utils.encode_cell({c: C, r: R});
if (C > newRef.e.c) {
newRef.e.c = C;
}
ws[encCell] = updateCellData(ws[encCell], cellVal[j]);
}
}
ws['!ref'] = xlsx.utils.encode_range(newRef);
return ws;
}
|
javascript
|
{
"resource": ""
}
|
q6997
|
writeCols
|
train
|
function writeCols(ws, cols, contents) {
let range = ws['!ref'];
range = check.undefined(range) ? 'A1:A1' : range;
let dRange = xlsx.utils.decode_range(range);
let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}};
let encCell;
if (typeof cols === 'string') {
cols = cols.split(',');
}
for (let i = 0; i < cols.length; ++i) {
let dCol = xlsx.utils.decode_col(cols[i]);
let cellVal = contents[i];
if (dCol > newRef.e.c) {
newRef.e.c = dCol;
}
for (let R = dRange.s.r; R < cellVal.length; ++R) {
encCell = xlsx.utils.encode_cell({c: dCol, r: R});
if (R > newRef.e.r) {
newRef.e.r = R;
}
ws[encCell] = updateCellData(ws[encCell], cellVal[R]);
}
}
ws['!ref'] = xlsx.utils.encode_range(newRef);
return ws;
}
|
javascript
|
{
"resource": ""
}
|
q6998
|
writeRows
|
train
|
function writeRows(ws, rows, contents) {
// console.log('Typeof Rows %s', typeof rows);
// console.log('Typeof Rows %s', rows);
// console.log('Length Rows %d', rows.length);
let range = ws['!ref'];
range = check.undefined(range) ? 'A1:A1' : range;
let dRange = xlsx.utils.decode_range(range);
let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}};
let encCell;
if (typeof rows === 'string') {
rows = rows.split(',');
}
for (let i = 0; i < rows.length; ++i) {
let dRow = xlsx.utils.decode_row(rows[i]);
let cellVal = contents[i];
// console.log('contents[%d]=%s', i, cellVal);
if (dRow > newRef.e.r) {
newRef.e.r = dRow;
}
for (let C = dRange.s.c; C < cellVal.length; ++C) {
encCell = xlsx.utils.encode_cell({c: C, r: dRow});
if (C > newRef.e.c) {
newRef.e.c = C;
}
ws[encCell] = updateCellData(ws[encCell], cellVal[C]);
}
}
ws['!ref'] = xlsx.utils.encode_range(newRef);
return ws;
}
|
javascript
|
{
"resource": ""
}
|
q6999
|
format
|
train
|
function format(opt_clangOptions, opt_clangFormat) {
var actualClangFormat = opt_clangFormat || clangFormat;
var optsStr = getOptsString(opt_clangOptions);
function formatFilter(file, enc, done) {
function onClangFormatFinished() {
file.contents = Buffer.from(formatted, 'utf-8');
done(null, file);
}
var formatted = '';
actualClangFormat(file, enc, optsStr, onClangFormatFinished)
.on('data', function(b) { formatted += b.toString(); })
.on('error', this.emit.bind(this, 'error'));
}
return through2.obj(formatFilter);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.