_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1300
|
getHeaderItems
|
train
|
function getHeaderItems (uid, currentDate, prvniZaslani, overeni) {
return {
attributes: {
uuid_zpravy: uid,
dat_odesl: formatDate(currentDate),
prvni_zaslani: formatBool(prvniZaslani, true),
overeni: formatBool(overeni, false)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q1301
|
getFooterItems
|
train
|
function getFooterItems (privateKey, items) {
const pkp = generatePKP(
privateKey,
items.dicPopl,
items.idProvoz,
items.idPokl,
items.poradCis,
formatDate(items.datTrzby),
formatNumber(items.celkTrzba)
)
const bkp = generateBKP(pkp)
return {
pkp: {
attributes: {
digest: 'SHA256',
cipher: 'RSA2048',
encoding: 'base64'
},
$value: pkp
},
bkp: {
attributes: {
digest: 'SHA1',
encoding: 'base16'
},
$value: bkp
}
}
}
|
javascript
|
{
"resource": ""
}
|
q1302
|
getResponseItems
|
train
|
function getResponseItems (response) {
const header = response.Hlavicka.attributes
const body = response.Potvrzeni.attributes
return {
uuid: header.uuid_zpravy,
bkp: header.bkp,
date: new Date(header.dat_prij),
test: body.test === 'true',
fik: body.fik,
warnings: getWarnings(response.Varovani)
}
}
|
javascript
|
{
"resource": ""
}
|
q1303
|
_loadUserFromToken
|
train
|
function _loadUserFromToken(){
return BB
.bind(this)
.then(function() {
return grasshopper.request(this.token).users.current();
})
.then(function(user){
this.user = user;
});
}
|
javascript
|
{
"resource": ""
}
|
q1304
|
_linkIdentity
|
train
|
function _linkIdentity() {
var identityOptions = {
id: this.params.raw.user_id,
accessToken: this.params.access_token,
accessSecret: this.params.access_secret,
screen_name: this.params.raw.screen_name
};
return BB.resolve(grasshopper.request(this.token).users.linkIdentity(this.user._id.toString(), 'twitter', identityOptions));
}
|
javascript
|
{
"resource": ""
}
|
q1305
|
makeVarMap
|
train
|
function makeVarMap(filename) {
var map = {vars: {}, media: {}, selector: {}};
function resolveImport(path, basedir) {
if (path[0] === '/')
return path;
if (path[0] === '.')
return pathResolve(join(basedir, path));
// webpack treats anything starting w/ ~ as a module name, which we're
// about to do below, so just remove leading tildes
path = path.replace(/^~/, '');
return resolve.sync(path, {
basedir: basedir,
packageFilter: function (package) {
var newPackage = extend({}, package);
if (newPackage.style != null)
newPackage.main = newPackage.style;
return newPackage;
}
});
}
function processRules(rule) {
// only variables declared for `:root` are supported for now
if (rule.type !== 'rule' ||
rule.selectors.length !== 1 ||
rule.selectors[0] !== ':root' ||
rule.parent.type !== 'root')
return;
rule.each(function (decl) {
var prop = decl.prop;
var value = decl.value;
if (prop && prop.indexOf('--') === 0)
map.vars[prop] = value;
});
}
function processAtRuleCustom(atRule) {
if (atRule.name && ['custom-media', 'custom-selector'].indexOf(atRule.name) !== -1) {
var type = atRule.name.split('-')[1];
var name = atRule.params.split(/\s+/, 1)[0];
var nameRe = new RegExp('^' + name + '\\s+');
map[type][name] = atRule.params.replace(nameRe, '');
}
}
function isUrl(string) {
return /(https?:)?\/\//.test(string);
}
function process(fn) {
var style = postcss().process(fs.readFileSync(fn, 'utf8'));
// recurse into each import. because we make the recursive call before
// extracting values (depth-first, post-order traversal), files that import
// libraries can re-define variable declarations, which more-closely
// matches the browser's behavior
style.root.eachAtRule(function (atRule) {
if (atRule.name !== 'import')
return;
var stripped = stripQuotes(unwrapUrl(atRule.params));
if(isUrl(stripped)) {
return;
}
process(resolveImport(stripped, dirname(fn)));
});
// extract variable definitions
style.root.eachRule(processRules);
// extract custom definitions
style.root.eachAtRule(processAtRuleCustom);
}
process(pathResolve(filename));
return map;
}
|
javascript
|
{
"resource": ""
}
|
q1306
|
prependTildesToImports
|
train
|
function prependTildesToImports(styles) {
styles.eachAtRule(function (atRule) {
if (atRule.name !== 'import')
return;
var stripped = stripQuotes(unwrapUrl(atRule.params));
if (stripped[0] !== '.' && stripped[0] !== '~' && stripped[0] !== '/') {
atRule.params = '"~' + stripped + '"';
}
});
}
|
javascript
|
{
"resource": ""
}
|
q1307
|
facebookReq
|
train
|
function facebookReq(req, res){
var redirectUrl = _.has(grasshopper.config.identities, 'facebook') ? grasshopper.config.identities.facebook.redirectUrl : 'defaultRoute';
BB.bind({token: req.session.token, params: req.query, res: res, req: req, user: null })
.then(function(){
if(!_.isUndefined(this.token)){
this.token = new Buffer(this.token, 'base64'); //A token exists, let's decode it
return _linkSocialAccount.call(this);
}
else {
return _createSocialAccount.call(this);
}
})
.then(function(){
res.redirect(redirectUrl);
})
.catch(function(err){
console.log(err.stack);
res.redirect(redirectUrl + '?error='+ err.message);
});
}
|
javascript
|
{
"resource": ""
}
|
q1308
|
SchemaMoment
|
train
|
function SchemaMoment(key, options) {
SchemaType.call(this, key, options);
this.get(function(val, self){
if(!val){
return val;
} else {
return new Moment(val);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q1309
|
PostgreStore
|
train
|
function PostgreStore(conString, options) {
if(!conString){
throw new Error('Connection String is missing.');
}
this._options = options || {};
this._options.pgstore = this._options.pgstore || {};
this._difficulty = this._options.pgstore.difficulty || 10;
this._table = this._options.pgstore.table || 'passwordless';
this._client = new pg.Pool({
connectionString: conString,
max: this._options.pgstore.pgPoolSize || 10
});
if(!isNumber(this._difficulty) || this._cost < 1) {
throw new Error('bcrypt difficulty must be an integer >= 1');
}
delete this._options.pgstore;
var self = this;
this._client.connect(function(err, client) {
if(err) {
throw new Error('Could not connect to Postgres database, with error : ' + err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q1310
|
oauth
|
train
|
function oauth(httpRequest, httpResponse){
var code = httpRequest.query.code,
redirectUrl = _.has(grasshopper.config.identities, 'google') ? grasshopper.config.identities.google.redirectUrl : 'defaultRoute';
grasshopper.auth('Google', { code: code })
.then(function(token) {
httpRequest.session.token = new Buffer(token).toString('base64');
httpRequest.session.save(function() {
httpResponse.redirect(redirectUrl+'/'+ httpRequest.session.token);
});
})
.fail(function(err){
httpResponse.redirect(redirectUrl+'/error='+ err.message);
});
}
|
javascript
|
{
"resource": ""
}
|
q1311
|
url
|
train
|
function url(httpRequest, httpResponse) {
var response = new Response(httpResponse);
grasshopper.googleAuthUrl()
.then(function(url) {
response.writeSuccess(url);
})
.fail(function(message) {
var err = {
code : 400,
message : message
};
response.writeError(err);
})
.done();
}
|
javascript
|
{
"resource": ""
}
|
q1312
|
parseHeader
|
train
|
function parseHeader(authHeader, callback){
try {
var parts=authHeader.split(/:/),
username=parts[0],
password=parts[1];
callback(null, {username: username, password: password});
}
catch(ex){
callback(ex);
}
}
|
javascript
|
{
"resource": ""
}
|
q1313
|
createConnection
|
train
|
function createConnection(port, host, options) {
if (isObject(port)) {
options = port;
}
else if (isObject(host)) {
options = host;
}
else if (isObject(options)) {
options = options;
}
else {
options = {};
}
if (isNumber(port)) {
options.port = port;
}
if (isString(host)) {
options.host = host;
}
debug('createConnection', options);
return tls.connect(options);
}
|
javascript
|
{
"resource": ""
}
|
q1314
|
bind
|
train
|
function bind(el, _ref) {
var modifiers = _ref.modifiers;
var target;
// Support children's modifier
target = modifiers.children ? Array.from(el.children) : el;
// Add balance text to the element
Vue.nextTick(function () {
return balanceText(target, {
watch: true
});
});
// Manually fire again later, like after styles are injected by Webpack
return setTimeout(function () {
return balanceText(target);
}, 300);
}
|
javascript
|
{
"resource": ""
}
|
q1315
|
componentUpdated
|
train
|
function componentUpdated(el, _ref2) {
var modifiers = _ref2.modifiers;
var target;
target = modifiers.children ? Array.from(el.children) : el;
return balanceText(target);
}
|
javascript
|
{
"resource": ""
}
|
q1316
|
date
|
train
|
function date (value) {
if (Object.prototype.toString.call(value) !== '[object Date]' || isNaN(value)) {
throw new Error(`Value '${value}' is not a date object.`)
}
}
|
javascript
|
{
"resource": ""
}
|
q1317
|
httpResponse
|
train
|
function httpResponse (response) {
if (!response) {
throw new Error('Unable to parse response.')
}
const errorAttrs = response.Chyba && response.Chyba.attributes
if (errorAttrs) {
throw new Error(`${response.Chyba.$value} (${errorAttrs.kod})`)
}
const body = response.Potvrzeni && response.Potvrzeni.attributes
const header = response.Hlavicka && response.Hlavicka.attributes
if (!body || !header) {
throw new Error('Unable to read response.')
}
}
|
javascript
|
{
"resource": ""
}
|
q1318
|
_createSocialAccount
|
train
|
function _createSocialAccount(){
return BB
.bind(this)
.then(function() {
return grasshopper.auth('Pinterest', this.params);
})
.then(function(token) {
this.req.session.token = new Buffer(token).toString('base64');
this.req.session.save();
});
}
|
javascript
|
{
"resource": ""
}
|
q1319
|
_linkSocialAccount
|
train
|
function _linkSocialAccount(){
return BB.bind(this)
.then(_loadUserFromToken)
.then(_getUserSocialDetails)
.then(_linkIdentity)
.catch(function(){
return _createSocialAccount.call(this); // Could not link account. Create one instead.
});
}
|
javascript
|
{
"resource": ""
}
|
q1320
|
_getUserSocialDetails
|
train
|
function _getUserSocialDetails(){
return BB
.bind(this)
.then(function() {
return pinterest
.query()
.get('me/?fields=id,first_name,last_name,url,username,image&access_token=' + this.params.access_token)
.request();
})
.then(function(res){
this.socialUserInfo = res[1].data;
});
}
|
javascript
|
{
"resource": ""
}
|
q1321
|
_linkIdentity
|
train
|
function _linkIdentity() {
var identityOptions = {
id: this.socialUserInfo.id,
accessToken: this.params.access_token,
screen_name: this.socialUserInfo.username
};
return BB.resolve(grasshopper.request(this.token).users.linkIdentity(this.user._id.toString(), 'pinterest', identityOptions));
}
|
javascript
|
{
"resource": ""
}
|
q1322
|
firstPass
|
train
|
function firstPass (loadedComponents, messages) {
messages.heading('Reference resolution - first pass')
const components = loadedComponents.blueprintComponents
const tymlyRefs = loadedComponents.blueprintRefs
const resolutions = findFirstPassResolutions(tymlyRefs, components)
if (!resolutions) {
messages.subHeading('Nothing to resolve')
return
}
resolveResolutions(resolutions, components, messages)
}
|
javascript
|
{
"resource": ""
}
|
q1323
|
getArrayOfHoles
|
train
|
function getArrayOfHoles(length) {
var holyLen = HOLY_ARRAY.length;
if (length > holyLen) {
HOLY_ARRAY.length = length;
for (var i = holyLen; i < length; ++i) {
HOLY_ARRAY[i] = ARRAY_HOLE_INDEX;
}
}
return HOLY_ARRAY.slice(0, length);
}
|
javascript
|
{
"resource": ""
}
|
q1324
|
train
|
function (what, oldProps, propName, val) {
Object.defineProperty(what, propName, {value: val, configurable: true, enumerable: true, writable: true});
}
|
javascript
|
{
"resource": ""
}
|
|
q1325
|
init
|
train
|
function init() {
/* jshint validthis: true */
// All construction is actually done in the init method.
if (!initializing) {
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
if(!this || (this.constructor !== Constructor) &&
// We are being called without `new` or we are extending.
arguments.length && Constructor.constructorExtends) {
dev.warn('can/construct/construct.js: extending a Construct without calling extend');
}
}
//!steal-remove-end
return (!this || this.constructor !== Constructor) &&
// We are being called without `new` or we are extending.
arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) :
// We are being called with `new`.
Constructor.newInstance.apply(Constructor, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
q1326
|
findMatch
|
train
|
function findMatch(filters, listener){
var handlers = [],
isMatch = true;
if( !_.isUndefined(listener.filters.nodes) && listener.filters.nodes.length > 0 ) {
isMatch = !_.isUndefined( _.find( listener.filters.nodes , function(node) {
return (node === filters.node || node === '*');
} ) );
}
if ( isMatch && !_.isUndefined(listener.filters.types) && listener.filters.types.length > 0 ) {
isMatch = !_.isUndefined( _.find( listener.filters.types , function(type) {
return (type === filters.type || type === '*');
} ) );
}
if( isMatch && !_.isUndefined(listener.filters.contentids) && listener.filters.contentids.length > 0 ) {
isMatch = !_.isUndefined( _.find( listener.filters.contentids , function(contentid) {
return (contentid === filters.contentid || contentid === '*');
} ) );
}
if( isMatch && !_.isUndefined(listener.filters.system) && listener.filters.system.length > 0 ) {
isMatch = !_.isUndefined( _.find( listener.filters.system , function(val) {
return (val === filters.system || val === '*');
} ) );
}
// If we still have a match return handlers attached to the listener
if( isMatch ) {
handlers = listener.handlers;
}
return handlers;
}
|
javascript
|
{
"resource": ""
}
|
q1327
|
filterListeners
|
train
|
function filterListeners (listenerCollection) {
return function(filters) {
var handlers = [];
_.each(listenerCollection, function(listener){
handlers = handlers.concat( findMatch(filters, listener) );
});
return handlers;
};
}
|
javascript
|
{
"resource": ""
}
|
q1328
|
Demux
|
train
|
function Demux(refs, limit) {
if (!(this instanceof Fireproof.Demux)) {
return new Fireproof.Demux(refs);
} else if (arguments.length > 1 && !Array.isArray(refs)) {
refs = Array.prototype.slice.call(arguments, 0);
}
this._limit = (limit !== undefined ? limit : true);
this._refs = refs;
this._positions = refs.reduce(function(positions, ref) {
positions[ref.ref().toString()] = {
name: undefined,
priority: undefined
};
return positions;
}, {});
// we always want there to be a "previous" promise to hang operations from
this._previousPromise = Fireproof.Promise.resolve([]);
this._buffer = [];
}
|
javascript
|
{
"resource": ""
}
|
q1329
|
createRelease
|
train
|
function createRelease(endpoint, version) {
return new Promise(function(resolve, reject) {
superagent
.post(endpoint)
.set(HEADERS)
.send({ version: version })
.end(function(err, res) {
if (!err) {
console.log('Sentry - Pushed release. Version: ' + version);
resolve(res);
} else {
reject(err);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q1330
|
uploadFile
|
train
|
function uploadFile(endpoint, releaseVersion, filePath) {
// sentry lets you use the tilde to indicate it just looks at relative locations
// instead of relying on the host/domain.
var IGNORE_DOMAIN = '~';
var staticBase = process.env.STATIC_BASE;
var IGNORE_PATH = staticBase ? url.parse(staticBase).path + '/' : '';
var CONFLICT_CODE = 409;
var fileData = path.parse(filePath);
var fileName = fileData.name + fileData.ext;
var sentryFilePath = IGNORE_DOMAIN + IGNORE_PATH + fileName;
return new Promise(function(resolve, reject) {
superagent
.post(endpoint)
.set(HEADERS)
.attach('file', filePath)
.field('name', sentryFilePath)
.end(function(err, res) {
if (!err) {
console.log('Sentry (release: ' + releaseVersion +
') - Successfully uploaded ' + fileName);
resolve();
} if (err && err.response && err.response.statusCode === CONFLICT_CODE) {
console.log('Sentry (' + releaseVersion + ') - ' + fileName +
' already exists.');
resolve();
} else {
reject(err);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q1331
|
uploadToSentry
|
train
|
function uploadToSentry(projectSlug, orgSlug, releaseVersion, assets) {
var releaseEndpoint = makeUrl(projectSlug, orgSlug);
var uploadEndpoint = releaseEndpoint + releaseVersion + '/files/';
createRelease(releaseEndpoint, releaseVersion)
.then(function() {
return Promise.all(assets.map(uploadFile.bind(null,
uploadEndpoint,
releaseVersion
)));
})
.catch(function(e) {
console.log('Release failed with error: ', e);
});
}
|
javascript
|
{
"resource": ""
}
|
q1332
|
tell
|
train
|
function tell(name, taskInfo) {
if (swig.tasks[name]) {
console.log(`Task '${name}' has been overridden by a local installation`.yellow);
}
swig.tasks[name] = _.extend({
description: '<unknown>',
flags: {},
}, taskInfo);
}
|
javascript
|
{
"resource": ""
}
|
q1333
|
train
|
function (file, unused, cb) {
if (file.isNull()) {
// nothing to do
return cb(null, file)
} else if (file.isStream()) {
// file.contents is a Stream. We don't support streams
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported!'))
} else if (file.isBuffer()) {
// lazy init the acss class
if (!acss) {
acss = new Atomizer()
if (addRules) {
acss.addRules(addRules)
}
}
// generate the class names and push them into the global collector array
var html = String(file.contents)
var classes = acss.findClassNames(html)
foundClasses = Array.prototype.concat(foundClasses, classes)
// make a note of this file if it's the newer than we've seen before
if (!latestMod || file.stat && file.stat.mtime > latestMod) {
latestFile = file
latestMod = file.stat && file.stat.mtime
}
// tell the engine we're done
cb()
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1334
|
do_save
|
train
|
function do_save(id, isnew) {
var mement = ent.data$(true, 'string')
if (undefined !== id) {
mement.id = id
}
mement.entity$ = ent.entity$
entmap[base] = entmap[base] || {}
entmap[base][name] = entmap[base][name] || {}
var prev = entmap[base][name][mement.id]
if (isnew && prev) {
return reply(error('entity-id-exists', { type: ent.entity$, id: id }))
}
var shouldMerge = true
if (options.merge !== false && ent.merge$ === false) {
shouldMerge = false
}
if (options.merge === false && ent.merge$ !== true) {
shouldMerge = false
}
mement = _.cloneDeep(mement)
if (shouldMerge) {
mement = _.assign(prev || {}, mement)
}
prev = entmap[base][name][mement.id] = mement
seneca.log.debug(function() {
return [
'save/' + (create ? 'insert' : 'update'),
ent.canon$({ string: 1 }),
mement,
desc
]
})
reply(null, ent.make$(prev))
}
|
javascript
|
{
"resource": ""
}
|
q1335
|
create_new
|
train
|
function create_new() {
var id
// Check if we already have an id or if
// we need to generate a new one.
if (undefined !== ent.id$) {
// Take a copy of the existing id and
// delete it from the ent object. Do
// save will handle the id for us.
id = ent.id$
delete ent.id$
// Save with the existing id
return do_save(id, true)
}
// Generate a new id
id = options.generate_id ? options.generate_id(ent) : void 0
if (undefined !== id) {
return do_save(id, true)
} else {
var gen_id = {
role: 'basic',
cmd: 'generate_id',
name: name,
base: base,
zone: zone
}
// When we get a respones we will use the id param
// as our entity id, if this fails we just fail and
// call reply() as we have no way to save without an id
seneca.act(gen_id, function(err, id) {
if (err) return reply(err)
do_save(id, true)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q1336
|
listents
|
train
|
function listents(seneca, entmap, qent, q, done) {
var list = []
var canon = qent.canon$({ object: true })
var base = canon.base
var name = canon.name
var entset = entmap[base] ? entmap[base][name] : null
if (entset) {
if (_.isString(q)) {
var ent = entset[q]
if (ent) {
list.push(ent)
}
}
if (_.isArray(q)) {
_.each(q, function(id) {
var ent = entset[id]
if (ent) {
ent = qent.make$(ent)
list.push(ent)
}
})
}
if (_.isObject(q)) {
_.keys(entset).forEach(function(id) {
var ent = entset[id]
for (var p in q) {
if (!~p.indexOf('$') && q[p] !== ent[p]) {
return
}
}
ent = qent.make$(ent)
list.push(ent)
})
}
}
// Always sort first, this is the 'expected' behaviour.
if (q.sort$) {
for (var sf in q.sort$) {
break
}
var sd = q.sort$[sf] < 0 ? -1 : 1
list = list.sort(function(a, b) {
return sd * (a[sf] < b[sf] ? -1 : a[sf] === b[sf] ? 0 : 1)
})
}
// Skip before limiting.
if (q.skip$ && q.skip$ > 0) {
list = list.slice(q.skip$)
}
// Limited the possibly sorted and skipped list.
if (q.limit$ && q.limit$ >= 0) {
list = list.slice(0, q.limit$)
}
// Prune fields
if (q.fields$) {
for (var i = 0; i < list.length; i++) {
var entfields = list[i].fields$()
for (var j = 0; j < entfields.length; j++) {
if ('id' !== entfields[j] && -1 == q.fields$.indexOf(entfields[j])) {
delete list[i][entfields[j]]
}
}
}
}
// Return the resulting list to the caller.
done.call(seneca, null, list)
}
|
javascript
|
{
"resource": ""
}
|
q1337
|
validateContentType
|
train
|
function validateContentType(cb) {
if (!_.isUndefined(kontx.args.meta) && !_.isUndefined(kontx.args.meta.type)) {
db.contentTypes.getById(kontx.args.meta.type.toString()).then(
function(contentType) {
cb(null, contentType);
},
function() {
cb(createError(400, messages.invalid_content_type));
});
} else {
cb(createError(400, messages.invalid_content_type));
}
}
|
javascript
|
{
"resource": ""
}
|
q1338
|
validateFields
|
train
|
function validateFields(contentType, cb) {
if (_.isArray(contentType.fields)) {
async.each(contentType.fields, validateField, function(err) {
cb(err);
});
} else {
cb();
}
}
|
javascript
|
{
"resource": ""
}
|
q1339
|
validateField
|
train
|
function validateField(field, cb) {
if (_.isArray(field.validation)) {
async.each(field.validation, performValidation(field), function(err) {
cb(err);
});
} else {
cb();
}
}
|
javascript
|
{
"resource": ""
}
|
q1340
|
performValidation
|
train
|
function performValidation(field) {
return function(rule, cb) {
var valueToBeValidated = kontx.args.fields[field._id],
validate = validator.get(rule);
//Undefined values do not need to be validated unless the field is required
if (rule.type === 'required' || !_.isUndefined(valueToBeValidated)) {
if (_.isArray(valueToBeValidated)) {
q.all(
_.map(valueToBeValidated, function(value) {
return validate(value, rule.options);
})
)
.then(
function() {
cb();
},
function() {
cb(createError(400, validationTemplate({
label: field.label
})));
}
);
} else {
validate(valueToBeValidated, rule.options)
.then(
function() {
cb();
},
function() {
cb(createError(400, validationTemplate({
label: field.label
})));
}
);
}
} else {
cb();
}
};
}
|
javascript
|
{
"resource": ""
}
|
q1341
|
_getPersistantFacebookToken
|
train
|
function _getPersistantFacebookToken(){
return facebook.query()
.get('/oauth/access_token?' +
'grant_type=fb_exchange_token&' +
'client_id=' + appId + '&' +
'client_secret=' + secret + '&' +
'fb_exchange_token=' + this.options.code)
.request()
.then(function (res) {
// Bad tokens result in a 200 with an error object
if (res[1].error) {
throw new Error(res[1].error.message);
}
this.creds = querystring.parse(res[1]);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q1342
|
_createNewFacebookUser
|
train
|
function _createNewFacebookUser() {
var avatar = '',
excludedFields = ['link', 'email', 'first_name', 'last_name','picture'],
newUser;
//Set Image
if(this.socialUserInfo.picture && this.socialUserInfo.picture.data && this.socialUserInfo.picture.data.url !== ''){
avatar = this.socialUserInfo.picture.data.url;
}
newUser = {
role: 'external',
identities: {
facebook: {
id: this.socialUserInfo.id,
accessToken: this.creds.access_token,
expiresIn: this.creds.expires
}
},
linkedidentities: ['facebook'],
profile: {
picture: avatar
},
enabled: true,
email: this.socialUserInfo.email,
firstname: this.socialUserInfo.first_name,
lastname: this.socialUserInfo.last_name
};
_.each(profileFieldsArr, function(field){
if(excludedFields.indexOf(field) === -1){
newUser.profile[field] = this.socialUserInfo[field];
}
}.bind(this));
return db.users.insert(newUser);
}
|
javascript
|
{
"resource": ""
}
|
q1343
|
_createNewToken
|
train
|
function _createNewToken() {
var token = uuid.v4(),
newTokenObj = {
_id: crypto.createHash(token, config.crypto.secret_passphrase),
uid: this.userInfo._id.toString(),
created: new Date().toISOString(),
type: 'facebook'
};
return db.tokens.insert(newTokenObj).then(function() { return token; });
}
|
javascript
|
{
"resource": ""
}
|
q1344
|
some
|
train
|
function some(iterable, n) {
if (n <= 0) return true;
for (let item of iterable) {
if (item && --n === 0) return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q1345
|
roleOrSelf
|
train
|
function roleOrSelf (role) {
if (!_.isNumber(role)) {
role = roles[role.toUpperCase()];
}
return function validateRoleOrSelf (kontx, next) {
var userPrivLevel = roles[kontx.user.role.toUpperCase()],
passedInUserId = kontx.args[0],
err = createError(strings.group('codes').forbidden, strings.group('errors').user_privileges_exceeded);
//If user object passed in instead of a string then parse.
if (!_.isUndefined(kontx.args[0]._id)) {
passedInUserId = kontx.args[0]._id;
}
//If user has enough priviliges then keep going
if (userPrivLevel <= parseInt(role, 10) || kontx.user._id.toString() === passedInUserId.toString()) {
next();
return;
}
next(err);
};
}
|
javascript
|
{
"resource": ""
}
|
q1346
|
setDefaultUser
|
train
|
function setDefaultUser (kontx, next) {
var a = _.clone(kontx.args);
if (a.length === 0) { //No args are sent in, set first to be user id
a[0] = kontx.user._id;
}
else if (_.has(a[0], 'include') || _.has(a[0], 'exclude')) { // If first arg is options then reassign
a[0] = kontx.user._id;
a[1] = kontx.args[0];
}
kontx.args = a;
next();
}
|
javascript
|
{
"resource": ""
}
|
q1347
|
train
|
function(options){
var cleanOptions = this.parseOptions(options),
excludes = _.clone(this.privateFields),
includeExludes = [];
// If any includes are passed in through the options clean up the
// default excluded fields. A type can have some excluded fields by
// default and if the user overrides this then we need to clean up the query.
if(options && options.include){
_.each(options.include, function(include){
//If the include matches an existing exclude then remove it from the
//excludes and also from the includes (you can't mix them)
excludes = _.remove(excludes, function(o){
if(o === include){
cleanOptions.include = _.remove(cleanOptions.include, function(i){
return i !== include;
});
}
return o !== include;
});
});
}
includeExludes = _.union(cleanOptions.include,
this.parseExclusion(cleanOptions.exclude),
this.parseExclusion(excludes)
);
return includeExludes.join(' ');
}
|
javascript
|
{
"resource": ""
}
|
|
q1348
|
Position
|
train
|
function Position(file, line, column) {
this.file = file;
this.line = line || 1;
this.column = column || 0;
}
|
javascript
|
{
"resource": ""
}
|
q1349
|
train
|
function () {
function draw(color, n) {
n = Math.max(parseInt(n), 0);
write(' ');
write('\u001b[' + color + 'm' + n + '\u001b[0m');
write('\n');
}
draw(colors.green, this.passed);
draw(colors.fail, this.failed);
draw(colors.pending, this.pending + ' ');
write('\n');
cursor.up(this.numberOfLines);
}
|
javascript
|
{
"resource": ""
}
|
|
q1350
|
train
|
function () {
var self = this;
this.trajectories.forEach(function(line, index) {
write('\u001b[' + self.scoreboardWidth + 'C');
write(line.join(''));
write('\n');
});
cursor.up(this.numberOfLines);
}
|
javascript
|
{
"resource": ""
}
|
|
q1351
|
train
|
function () {
var self = this;
var startWidth = this.scoreboardWidth + this.trajectories[0].length;
var color = '\u001b[' + startWidth + 'C';
var padding = '';
write(color);
write('_,------,');
write('\n');
write(color);
padding = self.tick ? ' ' : ' ';
write('_|' + padding + '/\\_/\\ ');
write('\n');
write(color);
padding = self.tick ? '_' : '__';
var tail = self.tick ? '~' : '^';
var face;
write(tail + '|' + padding + this.drawFace() + ' ');
write('\n');
write(color);
padding = self.tick ? ' ' : ' ';
write(padding + '"" "" ');
write('\n');
cursor.up(this.numberOfLines);
}
|
javascript
|
{
"resource": ""
}
|
|
q1352
|
_reduce
|
train
|
function _reduce(accumulator, iterable, initializer) {
for (let item of iterable) {
initializer = accumulator(initializer, item);
}
return initializer;
}
|
javascript
|
{
"resource": ""
}
|
q1353
|
compile
|
train
|
function compile() {
swig.log.info('', 'Compiling module list...');
const modulesPath = path.join(swig.temp, '/**/node_modules/@gilt-tech');
const modPaths = glob.sync(modulesPath);
let dirs;
swig.log.verbose(`[compile] searching: ${modulesPath}`);
swig.log.verbose(`[compile] found module directories: ${modPaths.length}`);
modPaths.forEach((modPath) => {
swig.log.verbose(`[compile] compiling: ${modPath}`);
dirs = fs.readdirSync(modPath);
_.each(dirs, (dir) => {
const dirPath = path.join(modPath, dir);
if (fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory()) {
azModules.push({ name: dir, path: dirPath });
}
});
});
// group by basename, and take the 'topmost' module in the hierarchy
azModules = _.groupBy(azModules, module => path.basename(module.path));
// pull out the 'winning' module path, for each module
azModules = _.map(azModules, (modulesList) => {
// the modules arg will be [{ name:, path: }, ...]
if (modulesList.length === 1) {
return modulesList[0];
}
// glob will almost always return the right order,
// but let's assert this to be safe. we can spare the cycles.
return _.sortBy(modulesList, module => module.path.length)[0];
});
// and now we pretty sort a-z for various output
// we dont reset azModules to the sorted array because we need it dirty for deps.less
_.sortBy(azModules, mod => mod.name).forEach((mod) => {
modules[mod.name] = mod.path;
});
swig.log.verbose('[compile] sorted modules: ');
swig.log.verbose(modules);
}
|
javascript
|
{
"resource": ""
}
|
q1354
|
Pager
|
train
|
function Pager(ref, initialCount) {
if (arguments.length < 1) {
throw new Error('Not enough arguments to Pager');
}
this._mainRef = ref.ref();
this._resetCurrentOperation();
this.hasNext = true;
this.hasPrevious = false;
var promise;
if (initialCount) {
promise = this.next(initialCount);
} else {
promise = Fireproof.Promise.resolve([]);
}
this.then = promise.then.bind(promise);
}
|
javascript
|
{
"resource": ""
}
|
q1355
|
flipImageData
|
train
|
function flipImageData (data, width, height) {
const numComponents = data.length / (width * height)
for (let y = 0; y < height / 2; y++) {
for (let x = 0; x < width; x++) {
for (let c = 0; c < numComponents; c++) {
const i = (y * width + x) * numComponents + c
const flippedI = ((height - y - 1) * width + x) * numComponents + c
const tmp = data[i]
data[i] = data[flippedI]
data[flippedI] = tmp
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q1356
|
deeplyExtendPkg
|
train
|
function deeplyExtendPkg(a, b) {
if(!a.resolutions) {
a.resolutions = {};
}
utils.extend(a.resolutions, b.resolutions || {});
if(!a.steal) {
a.steal = {};
}
if(!b.steal) {
b.steal = {};
}
utils.extend(a.steal, b.steal, true);
}
|
javascript
|
{
"resource": ""
}
|
q1357
|
loadChild
|
train
|
function loadChild(node, cb){
db.nodes.getByParent(node._id.toString()).then(
function(data){
payload = payload.concat(data);
async.each(data, loadChild, cb);
}).done();
}
|
javascript
|
{
"resource": ""
}
|
q1358
|
setNodes
|
train
|
function setNodes(data){
payload = data;
if(kontx.args.deep === true){
async.eachSeries(data, loadChild, sendNext);
}
else {
sendNext();
}
}
|
javascript
|
{
"resource": ""
}
|
q1359
|
train
|
function() {
if (!builds.length) { return; } // this shouldn't happen
var build = builds.shift();
var buildCallback = function(stats) {
cb(build.buildName, stats);
if (builds.length) {
runNextBuild();
}
};
console.log(colors.cyan('[Starting build]'), build.buildName);
executeBuild(build, buildCallback);
}
|
javascript
|
{
"resource": ""
}
|
|
q1360
|
train
|
function(){
var portHeight=parseFloat($("#workarea").css("height"));
var portWidth=parseFloat($("#workarea").css("width"));
var portX=$("#workarea").scrollLeft();
var portY=$("#workarea").scrollTop();
var windowWidth=parseFloat($("#svgcanvas").css("width"));
var windowHeight=parseFloat($("#svgcanvas").css("height"));
var overviewWidth=$("#overviewMiniView").attr("width");
var overviewHeight=$("#overviewMiniView").attr("height");
var viewBoxX=portX/windowWidth*overviewWidth;
var viewBoxY=portY/windowHeight*overviewHeight;
var viewBoxWidth=portWidth/windowWidth*overviewWidth;
var viewBoxHeight=portHeight/windowHeight*overviewHeight;
$("#overview_window_view_box").css("min-width",viewBoxWidth+"px");
$("#overview_window_view_box").css("min-height",viewBoxHeight+"px");
$("#overview_window_view_box").css("top",viewBoxY+"px");
$("#overview_window_view_box").css("left",viewBoxX+"px");
}
|
javascript
|
{
"resource": ""
}
|
|
q1361
|
train
|
function(){
var viewWidth=$("#svgroot").attr("width");
var viewHeight=$("#svgroot").attr("height");
var viewX=640;
var viewY=480;
if(svgedit.browser.isIE())
{
//This has only been tested with Firefox 10 and IE 9 (without chrome frame).
//I am not sure if if is Firefox or IE that is being non compliant here.
//Either way the one that is noncompliant may become more compliant later.
//TAG:HACK
//TAG:VERSION_DEPENDENT
//TAG:BROWSER_SNIFFING
viewX=0;
viewY=0;
}
var svgWidth_old=$("#overviewMiniView").attr("width");
var svgHeight_new=viewHeight/viewWidth*svgWidth_old;
$("#overviewMiniView").attr("viewBox",viewX+" "+viewY+" "+viewWidth+" "+viewHeight);
$("#overviewMiniView").attr("height",svgHeight_new);
updateViewBox();
}
|
javascript
|
{
"resource": ""
}
|
|
q1362
|
getLinked
|
train
|
function getLinked(elem, attr) {
var str = elem.getAttribute(attr);
if(!str) {return null;}
var m = str.match(/\(\#(.*)\)/);
if(!m || m.length !== 2) {
return null;
}
return S.getElem(m[1]);
}
|
javascript
|
{
"resource": ""
}
|
q1363
|
colorChanged
|
train
|
function colorChanged(elem) {
var color = elem.getAttribute('stroke');
$.each(mtypes, function(i, pos) {
var marker = getLinked(elem, 'marker-'+pos);
if (!marker) {return;}
if (!marker.attributes.se_type) {return;} // not created by this extension
var ch = marker.lastElementChild;
if (!ch) {return;}
var curfill = ch.getAttribute('fill');
var curstroke = ch.getAttribute('stroke');
if (curfill && curfill != 'none') {ch.setAttribute('fill', color);}
if (curstroke && curstroke != 'none') {ch.setAttribute('stroke', color);}
});
}
|
javascript
|
{
"resource": ""
}
|
q1364
|
updateReferences
|
train
|
function updateReferences(el) {
$.each(mtypes, function (i, pos) {
var id = marker_prefix + pos + '_' + el.id;
var marker_name = 'marker-'+pos;
var marker = getLinked(el, marker_name);
if (!marker || !marker.attributes.se_type) {return;} // not created by this extension
var url = el.getAttribute(marker_name);
if (url) {
var len = el.id.length;
var linkid = url.substr(-len-1, len);
if (el.id != linkid) {
var val = $('#'+pos + '_marker').attr('value');
addMarker(id, val);
svgCanvas.changeSelectedAttribute(marker_name, "url(#" + id + ")");
if (el.tagName === 'line' && pos == 'mid') {el = convertline(el);}
S.call("changed", selElems);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q1365
|
train
|
function(elem) {
try {
// TODO: Fix issue with rotated groups. Currently they work
// fine in FF, but not in other browsers (same problem mentioned
// in Issue 339 comment #2).
var bb = svgedit.utilities.getBBox(elem);
var angle = svgedit.utilities.getRotationAngle(elem);
if ((angle && angle % 90) ||
svgedit.math.hasMatrixTransform(svgedit.transformlist.getTransformList(elem))) {
// Accurate way to get BBox of rotated element in Firefox:
// Put element in group and get its BBox
var good_bb = false;
// Get the BBox from the raw path for these elements
var elemNames = ['ellipse', 'path', 'line', 'polyline', 'polygon'];
if (elemNames.indexOf(elem.tagName) >= 0) {
bb = good_bb = canvas.convertToPath(elem, true);
} else if (elem.tagName == 'rect') {
// Look for radius
var rx = elem.getAttribute('rx');
var ry = elem.getAttribute('ry');
if (rx || ry) {
bb = good_bb = canvas.convertToPath(elem, true);
}
}
if (!good_bb) {
// Must use clone else FF freaks out
var clone = elem.cloneNode(true);
var g = document.createElementNS(NS.SVG, "g");
var parent = elem.parentNode;
parent.appendChild(g);
g.appendChild(clone);
bb = svgedit.utilities.bboxToObj(g.getBBox());
parent.removeChild(g);
}
// Old method: Works by giving the rotated BBox,
// this is (unfortunately) what Opera and Safari do
// natively when getting the BBox of the parent group
// var angle = angle * Math.PI / 180.0;
// var rminx = Number.MAX_VALUE, rminy = Number.MAX_VALUE,
// rmaxx = Number.MIN_VALUE, rmaxy = Number.MIN_VALUE;
// var cx = round(bb.x + bb.width/2),
// cy = round(bb.y + bb.height/2);
// var pts = [ [bb.x - cx, bb.y - cy],
// [bb.x + bb.width - cx, bb.y - cy],
// [bb.x + bb.width - cx, bb.y + bb.height - cy],
// [bb.x - cx, bb.y + bb.height - cy] ];
// var j = 4;
// while (j--) {
// var x = pts[j][0],
// y = pts[j][1],
// r = Math.sqrt( x*x + y*y );
// var theta = Math.atan2(y,x) + angle;
// x = round(r * Math.cos(theta) + cx);
// y = round(r * Math.sin(theta) + cy);
//
// // now set the bbox for the shape after it's been rotated
// if (x < rminx) rminx = x;
// if (y < rminy) rminy = y;
// if (x > rmaxx) rmaxx = x;
// if (y > rmaxy) rmaxy = y;
// }
//
// bb.x = rminx;
// bb.y = rminy;
// bb.width = rmaxx - rminx;
// bb.height = rmaxy - rminy;
}
return bb;
} catch(e) {
console.log(elem, e);
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1366
|
train
|
function(m) {
console.log([m.a, m.b, m.c, m.d, m.e, m.f]);
}
|
javascript
|
{
"resource": ""
}
|
|
q1367
|
sanitizeSpontaneousAreas
|
train
|
function sanitizeSpontaneousAreas(req, data, page, callback) {
var toSanitize = [];
_.each(data, function(val, key) {
if (typeof(val) === 'object') {
if (val.type === 'area') {
if (_.has(page, key) && ((typeof(page[key]) !== 'object') || (page[key].type !== 'area'))) {
// Spontaneous areas may not replace properties that are not areas
return;
}
toSanitize.push({ key: key, items: val.items });
}
}
});
return async.eachSeries(toSanitize, function(entry, callback) {
return apos.sanitizeItems(req, entry.items || [], function(err, _items) {
if (err) {
return callback(err);
}
entry.items = _items;
return callback(null);
});
}, function(err) {
if (err) {
return callback(err);
}
_.each(toSanitize, function(entry) {
page[entry.key] = { type: 'area', items: entry.items };
});
return callback(null);
});
}
|
javascript
|
{
"resource": ""
}
|
q1368
|
diffVersions
|
train
|
function diffVersions(callback) {
var prior = null;
_.each(versions, function(version) {
if (!prior) {
version.diff = [ { value: '[NEW]', added: true } ];
} else {
version.diff = apos.diffPages(prior, version);
}
prior = version;
});
versions.reverse();
return callback(null);
}
|
javascript
|
{
"resource": ""
}
|
q1369
|
getId
|
train
|
function getId(id){
if(_.isObject(id) && !_.isUndefined(id.id)){
if (objectIdRegex.test(id.id)) {
id = id.id;
}
else {
id = null;
}
}
return id;
}
|
javascript
|
{
"resource": ""
}
|
q1370
|
init
|
train
|
function init() {
// Make sure all connectors have data set
$(svgcontent).find('*').each(function() {
var conn = this.getAttributeNS(se_ns, "connector");
if(conn) {
this.setAttribute('class', conn_sel.substr(1));
var conn_data = conn.split(' ');
var sbb = svgCanvas.getStrokedBBox([getElem(conn_data[0])]);
var ebb = svgCanvas.getStrokedBBox([getElem(conn_data[1])]);
$(this).data('c_start',conn_data[0])
.data('c_end',conn_data[1])
.data('start_bb', sbb)
.data('end_bb', ebb);
svgCanvas.getEditorNS(true);
}
});
// updateConnectors();
}
|
javascript
|
{
"resource": ""
}
|
q1371
|
error
|
train
|
function error(err) {
if (!(err instanceof Error)) return err
return {
code: err.code,
message: err.message,
details: err.detail,
stack: err.stack || ''
}
}
|
javascript
|
{
"resource": ""
}
|
q1372
|
Segment
|
train
|
function Segment(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1373
|
SegmentMeta
|
train
|
function SegmentMeta(properties) {
this.evidences = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1374
|
Evidence
|
train
|
function Evidence(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1375
|
Link
|
train
|
function Link(properties) {
this.signatures = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1376
|
Process
|
train
|
function Process(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1377
|
LinkMeta
|
train
|
function LinkMeta(properties) {
this.refs = [];
this.tags = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1378
|
LinkReference
|
train
|
function LinkReference(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1379
|
Signature
|
train
|
function Signature(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q1380
|
proxy
|
train
|
function proxy(func){
'use strict';
// Returns a middleware
return function (kontx, next){
func(kontx.args).then(
function(payload){
kontx.payload = payload;
next();
},
function(err){
next(err);
}
);
};
}
|
javascript
|
{
"resource": ""
}
|
q1381
|
train
|
function(index, obj) {
var lang = this.lang;
var lindex = index.toLowerCase();
if(typeof obj == "object") {
lang = obj;
}
if(lang && lang[lindex]) {
return lang[lindex];
}
return index;
}
|
javascript
|
{
"resource": ""
}
|
|
q1382
|
train
|
function(callback) {
this.face.stop();
this.timer.stop(callback);
for(var x in this.lists) {
this.lists[x].stop();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1383
|
train
|
function(label, css, excludeDots) {
if(typeof css == "boolean" || !css) {
excludeDots = css;
css = label;
}
var dots = [
'<span class="'+this.factory.classes.dot+' top"></span>',
'<span class="'+this.factory.classes.dot+' bottom"></span>'
].join('');
if(excludeDots) {
dots = '';
}
label = this.factory.localize(label);
var html = [
'<span class="'+this.factory.classes.divider+' '+(css ? css : '').toLowerCase()+'">',
'<span class="'+this.factory.classes.label+'">'+(label ? label : '')+'</span>',
dots,
'</span>'
];
return $(html.join(''));
}
|
javascript
|
{
"resource": ""
}
|
|
q1384
|
train
|
function(digit) {
var obj = this.createList(digit, {
classes: {
active: this.factory.classes.active,
before: this.factory.classes.before,
flip: this.factory.classes.flip
}
});
obj.$obj.insertBefore(this.factory.lists[0].$obj);
this.factory.lists.unshift(obj);
}
|
javascript
|
{
"resource": ""
}
|
|
q1385
|
train
|
function() {
var t = this;
setTimeout(function() {
t.$obj.removeClass(t.factory.classes.play);
}, this.factory.timer.interval);
}
|
javascript
|
{
"resource": ""
}
|
|
q1386
|
validateFieldType
|
train
|
function validateFieldType(fieldsCollection){
var err;
// ensure fieldsCollection is an array.
if(!_.isArray(fieldsCollection)) {
err = new Error('content type fields collection must be an array of field objects.');
}
if(!err) {
_.each(fieldsCollection, function(field){
err = isValidField(field);
});
}
return _.isUndefined(err);
}
|
javascript
|
{
"resource": ""
}
|
q1387
|
_setUserInfoFromSocialAccount
|
train
|
function _setUserInfoFromSocialAccount(){
return db.users.socialAuthentication('twitter', this.socialUserInfo.id_str)
.then(function(user){
this.userInfo = user;
}.bind(this))
.catch(function(err){ // If user isn't found surpress error. If found and still error then throw.
if(err.code !== 404){
throw(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q1388
|
train
|
function(token){
return {
users: require('./runners/users')(token),
tokens: require('./runners/tokens')(token),
content: require('./runners/content')(token),
contentTypes: require('./runners/contentTypes')(token),
nodes: require('./runners/nodes')(token),
assets: require('./runners/assets')(token),
system: require('./runners/system')(token)
};
}
|
javascript
|
{
"resource": ""
}
|
|
q1389
|
findType
|
train
|
function findType (node, typeInfo, nestedCall) {
typeInfo = typeInfo || { noNull: false, isArray: false, noNullArrayValues: false }
if (!node) {
return typeInfo
}
// Validate nested call, the parser will check first if the array can be null
// then it will check if the values inside can be null
if (!nestedCall && node.kind === 'NonNullType') {
typeInfo.noNull = true
}
// If it is an array, validate if the values inside can be null
if (nestedCall && typeInfo.isArray && node.kind === 'NonNullType') {
typeInfo.noNullArrayValues = true
}
if (node.kind === 'ListType') {
typeInfo.isArray = true
}
if (node.name) {
typeInfo.type = node.name.value
}
return findType(node.type, typeInfo, true)
}
|
javascript
|
{
"resource": ""
}
|
q1390
|
findArguments
|
train
|
function findArguments (node) {
if (!node) {
return []
}
return node.map(arg => {
const name = arg.name.value
const fieldType = findType(arg.type)
const isDeprecated = validateIfDeprecated(arg.directives)
return Object.assign({ name, isDeprecated }, fieldType)
})
}
|
javascript
|
{
"resource": ""
}
|
q1391
|
validateIfDeprecated
|
train
|
function validateIfDeprecated (directives) {
if (!directives.length) {
return false
}
return directives.some(directive => directive.name.value === 'deprecated')
}
|
javascript
|
{
"resource": ""
}
|
q1392
|
min
|
train
|
function min(compare, iterable, dflt = undefined) {
let iterator = (0, _iter.iter)(iterable);
let first = iterator.next();
if (first.done) return dflt;
let smallest = first.value;
for (let candidate of iterator) {
if (compare(candidate, smallest) < 0) {
smallest = candidate;
}
}
return smallest;
}
|
javascript
|
{
"resource": ""
}
|
q1393
|
toNLCST
|
train
|
function toNLCST(tree, file, Parser, options) {
var settings = options || {}
var parser
// Warn for invalid parameters.
if (!tree || !tree.type) {
throw new Error('mdast-util-to-nlcst expected node')
}
if (!file || !file.messages) {
throw new Error('mdast-util-to-nlcst expected file')
}
// Construct parser.
if (!Parser) {
throw new Error('mdast-util-to-nlcst expected parser')
}
if (
!tree.position ||
!tree.position.start ||
!tree.position.start.column ||
!tree.position.start.line
) {
throw new Error('mdast-util-to-nlcst expected position on nodes')
}
parser = 'parse' in Parser ? Parser : new Parser()
// Transform mdast into NLCST tokens, and pass these into `parser.parse` to
// insert sentences, paragraphs where needed.
return parser.parse(
one(
{
doc: String(file),
location: vfileLocation(file),
parser: parser,
ignore: ignore.concat(settings.ignore || []),
source: source.concat(settings.source || [])
},
tree
)
)
}
|
javascript
|
{
"resource": ""
}
|
q1394
|
one
|
train
|
function one(config, node) {
var offset = config.location.toOffset
var parser = config.parser
var doc = config.doc
var type = node.type
var start = offset(position.start(node))
var end = offset(position.end(node))
if (config.ignore.indexOf(type) === -1) {
if (config.source.indexOf(type) !== -1) {
return patch(
config,
[parser.tokenizeSource(doc.slice(start, end))],
start
)
}
if (node.children) {
return all(config, node)
}
if (type === 'image' || type === 'imageReference') {
return patch(config, parser.tokenize(node.alt), start + 2)
}
if (type === 'text' || type === 'escape') {
return patch(config, parser.tokenize(node.value), start)
}
if (node.type === 'break') {
return patch(config, [parser.tokenizeWhiteSpace('\n')], start)
}
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q1395
|
patch
|
train
|
function patch(config, nodes, offset) {
var position = config.location.toPosition
var length = nodes.length
var index = -1
var start = offset
var children
var node
var end
while (++index < length) {
node = nodes[index]
children = node.children
if (children) {
patch(config, children, start)
}
end = start + toString(node).length
node.position = {start: position(start), end: position(end)}
start = end
}
return nodes
}
|
javascript
|
{
"resource": ""
}
|
q1396
|
reduce
|
train
|
function reduce(accumulator, iterable, initializer = undefined) {
if (initializer === undefined) {
const iterator = (0, _iter.iter)(iterable);
const first = iterator.next();
if (first.done) {
return undefined;
}
return (0, _reduce2._reduce)(accumulator, iterator, first.value);
}
return (0, _reduce2._reduce)(accumulator, iterable, initializer);
}
|
javascript
|
{
"resource": ""
}
|
q1397
|
train
|
function(loader, name){
var pkg = utils.pkg.findByName(loader, name.split("/")[0]);
if(pkg) {
var parsed = utils.moduleName.parse(name, pkg.name);
parsed.version = pkg.version;
if(!parsed.modulePath) {
parsed.modulePath = utils.pkg.main(pkg);
}
return utils.moduleName.create(parsed);
}
return name;
}
|
javascript
|
{
"resource": ""
}
|
|
q1398
|
train
|
function(callback) {
var page = apos.data.aposPages.page;
var _id = page._id;
$.get('/apos-pages/info', { _id: _id }, function(data) {
var newPathname = data.slug.replace(/^\/\//, '/');
apos.redirect(newPathname);
}).error(function() {
// If the page no longer exists, navigate away to home page
apos.redirect('/');
});
}
|
javascript
|
{
"resource": ""
}
|
|
q1399
|
loadBootstrap
|
train
|
function loadBootstrap(appPath, modules, type = 'worker') {
let bootstrapPath = '';
if (modules.length) {
bootstrapPath = path.join(appPath, 'common/bootstrap');
} else {
bootstrapPath = path.join(appPath, 'bootstrap');
}
const filepath = path.join(bootstrapPath, `${type}.js`);
if (helper.isFile(filepath)) {
debug(`load file: ${filepath}`);
return require(filepath);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.