_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q29000 | getEmberImportAliasName | train | function getEmberImportAliasName(importDeclaration) {
if (!importDeclaration.source) return null;
if (importDeclaration.source.value !== 'ember') return null;
return importDeclaration.specifiers[0].local.name;
} | javascript | {
"resource": ""
} |
q29001 | hasDuplicateDependentKeys | train | function hasDuplicateDependentKeys(callExp) {
if (!isComputedProp(callExp)) return false;
const dependentKeys = parseDependentKeys(callExp);
const uniqueKeys = dependentKeys
.filter((val, index, self) => self.indexOf(val) === index);
return uniqueKeys.length !== dependentKeys.length;
} | javascript | {
"resource": ""
} |
q29002 | parseDependentKeys | train | function parseDependentKeys(callExp) {
// Check whether we have a MemberExpression, eg. computed(...).volatile()
const isMemberExpCallExp = !callExp.arguments.length &&
utils.isMemberExpression(callExp.callee) &&
utils.isCallExpression(callExp.callee.object);
const args = isMemberExpCallExp ? callExp.callee.object.arguments : callExp.arguments;
const dependentKeys = args
.filter(arg => utils.isLiteral(arg))
.map(literal => literal.value);
return unwrapBraceExpressions(dependentKeys);
} | javascript | {
"resource": ""
} |
q29003 | unwrapBraceExpressions | train | function unwrapBraceExpressions(dependentKeys) {
const braceExpressionRegexp = /{.+}/g;
const unwrappedExpressions = dependentKeys.map((key) => {
if (typeof key !== 'string' || !braceExpressionRegexp.test(key)) return key;
const braceExpansionPart = key.match(braceExpressionRegexp)[0];
const prefix = key.replace(braceExpansionPart, '');
const properties = braceExpansionPart
.replace('{', '')
.replace('}', '')
.split(',');
return properties.map(property => `${prefix}${property}`);
});
return unwrappedExpressions
.reduce((acc, cur) => acc.concat(cur), []);
} | javascript | {
"resource": ""
} |
q29004 | findStmtNodes | train | function findStmtNodes(nodeBody) {
const nodes = [];
const fnExpressions = utils.findNodes(nodeBody, 'ExpressionStatement');
const returnStatement = utils.findNodes(nodeBody, 'ReturnStatement');
if (fnExpressions.length !== 0) {
fnExpressions.forEach((item) => {
nodes.push(item);
});
}
if (returnStatement.length !== 0) {
returnStatement.forEach((item) => {
nodes.push(item);
});
}
return nodes;
} | javascript | {
"resource": ""
} |
q29005 | checkForSuper | train | function checkForSuper(nodes) {
if (nodes.length === 0) return false;
return nodes.some((n) => {
if (utils.isCallExpression(n.expression)) {
const fnCallee = n.expression.callee;
return utils.isMemberExpression(fnCallee) &&
utils.isThisExpression(fnCallee.object) &&
utils.isIdentifier(fnCallee.property) &&
fnCallee.property.name === '_super';
} else if (utils.isReturnStatement(n)) {
if (!n.argument || !utils.isCallExpression(n.argument)) return false;
const fnCallee = n.argument.callee;
return fnCallee.property.name === '_super';
}
return false;
});
} | javascript | {
"resource": ""
} |
q29006 | saveNewVersion | train | function saveNewVersion(version, versionFile) {
fs.writeFileSync(versionFile, JSON.stringify({
version
}, null, 2), 'UTF-8');
} | javascript | {
"resource": ""
} |
q29007 | getSettings | train | function getSettings(desktopPath) {
let settings = {};
try {
settings = JSON.parse(
fs.readFileSync(path.join(desktopPath, 'settings.json'), 'UTF-8')
);
} catch (e) {
return {};
}
return settings;
} | javascript | {
"resource": ""
} |
q29008 | getFileList | train | function getFileList(dir, sort = true) {
return new Promise((resolve, reject) => {
readdir(dir, (error, files) => {
if (error) {
reject(error);
return;
}
let resultantFilesList;
if (sort) {
const stripLength = (dir.substr(0, 2) === './') ? dir.length - 1 : dir.length + 1;
let pathsUnified = files.map((pth => pth.substr(stripLength).replace(/[\\/]/gm, '-')));
const temporaryIndex = {};
files.forEach((file, i) => {
temporaryIndex[pathsUnified[i]] = file;
});
pathsUnified = pathsUnified.sort();
const filesSorted = [];
pathsUnified.forEach((key) => {
filesSorted.push(temporaryIndex[key]);
});
resultantFilesList = filesSorted;
} else {
resultantFilesList = files;
}
resolve(resultantFilesList);
});
});
} | javascript | {
"resource": ""
} |
q29009 | readAndHashFiles | train | function readAndHashFiles(files) {
const fileHashes = {};
const fileContents = {};
const promises = [];
function readSingleFile(file) {
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
console.log(err);
reject(err);
return;
}
const hash = crypto.createHash('sha1');
hash.update(data);
const bufferHash = hash.digest();
fileHashes[file] = bufferHash.toString('hex');
if (file.endsWith('.js') && !file.endsWith('.test.js')) {
fileContents[file] = data.toString('utf8');
}
resolve();
});
});
}
files.forEach((file) => {
promises.push(readSingleFile(file));
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(() => {
resolve({ files, fileContents, fileHashes });
})
.catch(reject);
});
} | javascript | {
"resource": ""
} |
q29010 | readFilesAndComputeDesktopHash | train | function readFilesAndComputeDesktopHash(dir) {
const desktopHash = crypto.createHash('sha1');
return new Promise((resolve, reject) => {
getFileList(dir)
.catch(reject)
.then(readAndHashFiles)
.catch(reject)
.then((result) => {
const hash = result.files.reduce(
(tmpHash, file) => {
tmpHash += result.fileHashes[file];
return tmpHash;
}, ''
);
desktopHash.update(hash);
result.hash = desktopHash.digest('hex');
resolve(result);
});
});
} | javascript | {
"resource": ""
} |
q29011 | removeDir | train | function removeDir(dirPath, delay = 0) {
return new Promise((resolve, reject) => {
setTimeout(() => {
rimraf(dirPath, {
maxBusyTries: 100
}, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
}, delay);
});
} | javascript | {
"resource": ""
} |
q29012 | ManifestEntry | train | function ManifestEntry(manifestEntry) {
assignIn(this, {
filePath: manifestEntry.path,
urlPath: manifestEntry.url,
fileType: manifestEntry.type,
size: manifestEntry.size,
cacheable: manifestEntry.cacheable,
hash: manifestEntry.hash || null,
sourceMapFilePath: manifestEntry.sourceMap || null,
sourceMapUrlPath: manifestEntry.sourceMapUrl || null
});
} | javascript | {
"resource": ""
} |
q29013 | createStreamProtocolResponse | train | function createStreamProtocolResponse(filePath, res, beforeFinalize) {
if (!fs.existsSync(filePath)) {
return;
}
// Setting file size.
const stat = fs.statSync(filePath);
res.setHeader('Content-Length', stat.size);
// Setting last modified date.
const modified = stat.mtime.toUTCString();
res.setHeader('Last-Modified', modified);
// Determining mime type.
const type = mime.getType(filePath);
if (type) {
const charset = mime.getExtension(type);
res.setHeader('Content-Type', type + (charset ? `; charset=${charset}` : ''));
} else {
res.setHeader('Content-Type', 'application/octet-stream');
}
res.setHeader('Connection', 'close');
res.setStream(fs.createReadStream(filePath));
res.setStatusCode(200);
beforeFinalize();
res.finalize();
} | javascript | {
"resource": ""
} |
q29014 | respondWithCode | train | function respondWithCode(res, code, message) {
/* eslint-disable */
res._headers = {};
res._headerNames = {};
res.statusCode = code;
/* eslint-enable */
res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
res.setHeader('Content-Length', Buffer.byteLength(message));
res.setHeader('X-Content-Type-Options', 'nosniff');
res.end(message);
} | javascript | {
"resource": ""
} |
q29015 | AssetHandler | train | function AssetHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
// Check if we have an asset for that url defined.
/** @type {Asset} */
const asset = self.assetBundle.assetForUrlPath(parsedUrl.pathname);
if (!asset) return next();
const processors = () => (
addSourceMapHeader(asset, res),
addETagHeader(asset, res),
addCacheHeader(asset, res, req.url)
);
if (local) {
return createStreamProtocolResponse(asset.getFile(), res, processors);
}
return send(
req,
encodeURIComponent(asset.getFile()),
{ etag: false, cacheControl: false }
)
.on('file', processors)
.pipe(res);
} | javascript | {
"resource": ""
} |
q29016 | WwwHandler | train | function WwwHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
if (parsedUrl.pathname !== '/cordova.js') {
return next();
}
const parentAssetBundle = self.assetBundle.getParentAssetBundle();
// We need to obtain a path for the initial asset bundle which usually is the parent
// asset bundle, but if there were not HCPs yet, the main asset bundle is the
// initial one.
const initialAssetBundlePath =
parentAssetBundle ?
parentAssetBundle.getDirectoryUri() : self.assetBundle.getDirectoryUri();
const filePath = path.join(initialAssetBundlePath, parsedUrl.pathname);
if (fs.existsSync(filePath)) {
return local ?
createStreamProtocolResponse(filePath, res, () => {
}) :
send(req, encodeURIComponent(filePath)).pipe(res);
}
return next();
} | javascript | {
"resource": ""
} |
q29017 | FilesystemHandler | train | function FilesystemHandler(req, res, next, urlAlias, localPath, local = false) {
const parsedUrl = url.parse(req.url);
if (!parsedUrl.pathname.startsWith(urlAlias)) {
return next();
}
const bareUrl = parsedUrl.pathname.substr(urlAlias.length);
let filePath;
if (localPath) {
filePath = path.join(localPath, decodeURIComponent(bareUrl));
if (filePath.toLowerCase().lastIndexOf(localPath.toLowerCase(), 0) !== 0) {
return respondWithCode(res, 400, 'Wrong path.');
}
} else {
filePath = decodeURIComponent(bareUrl);
}
if (fs.existsSync(filePath)) {
return local ?
createStreamProtocolResponse(filePath, res, () => {
}) :
send(req, encodeURIComponent(filePath)).pipe(res);
}
return local ? res.setStatusCode(404) : respondWithCode(res, 404, 'File does not exist.');
} | javascript | {
"resource": ""
} |
q29018 | LocalFilesystemHandler | train | function LocalFilesystemHandler(req, res, next, local = false) {
if (!self.settings.localFilesystem) {
return next();
}
return FilesystemHandler(req, res, next, self.localFilesystemUrl, undefined, local);
} | javascript | {
"resource": ""
} |
q29019 | DesktopAssetsHandler | train | function DesktopAssetsHandler(req, res, next, local = false) {
return FilesystemHandler(req, res, next, self.desktopAssetsUrl, path.join(desktopPath, 'assets'), local);
} | javascript | {
"resource": ""
} |
q29020 | IndexHandler | train | function IndexHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
if (!parsedUrl.pathname.startsWith(self.localFilesystemUrl) &&
parsedUrl.pathname !== '/favicon.ico'
) {
/** @type {Asset} */
const indexFile = self.assetBundle.getIndexFile();
if (local) {
createStreamProtocolResponse(indexFile.getFile(), res, () => {
});
} else {
send(req, encodeURIComponent(indexFile.getFile())).pipe(res);
}
} else {
next();
}
} | javascript | {
"resource": ""
} |
q29021 | Asset | train | function Asset(filePath, urlPath, fileType, cacheable, hash, sourceMapUrlPath, size, bundle) {
this.filePath = filePath;
this.urlPath = urlPath;
this.fileType = fileType;
this.cacheable = cacheable;
this.hash = hash;
this.entrySize = size;
this.sourceMapUrlPath = sourceMapUrlPath;
this.bundle = bundle;
this.getFile = function getFile() {
return path.join(this.bundle.directoryUri, filePath);
};
} | javascript | {
"resource": ""
} |
q29022 | isEmptySync | train | function isEmptySync(searchPath) {
let stat;
try {
stat = fs.statSync(searchPath);
} catch (e) {
return true;
}
if (stat.isDirectory()) {
const items = fs.readdirSync(searchPath);
return !items || !items.length;
}
return false;
} | javascript | {
"resource": ""
} |
q29023 | rimrafWithRetries | train | function rimrafWithRetries(...args) {
let retries = 0;
return new Promise((resolve, reject) => {
function rm(...rmArgs) {
try {
rimraf.sync(...rmArgs);
resolve();
} catch (e) {
retries += 1;
if (retries < 5) {
setTimeout(() => {
rm(...rmArgs);
}, 100);
} else {
reject(e);
}
}
}
rm(...args);
});
} | javascript | {
"resource": ""
} |
q29024 | setExtMap | train | function setExtMap(map, extname, val) {
if (extname && extname.indexOf('.') === 0) {
extname = extname.substring(1);
}
if (!extname) {
return;
}
map[extname] = val;
} | javascript | {
"resource": ""
} |
q29025 | train | function(json) {
var decoder = AV.Op._opDecoderMap[json.__op];
if (decoder) {
return decoder(json);
} else {
return undefined;
}
} | javascript | {
"resource": ""
} | |
q29026 | train | function(options) {
if (!this.id)
return Promise.reject(new Error('The status id is not exists.'));
var request = AVRequest('statuses', null, this.id, 'DELETE', options);
return request;
} | javascript | {
"resource": ""
} | |
q29027 | train | function(options = {}) {
if (!getSessionToken(options) && !AV.User.current()) {
throw new Error('Please signin an user.');
}
if (!this.query) {
return AV.Status.sendStatusToFollowers(this, options);
}
return getUserPointer(options)
.then(currUser => {
var query = this.query.toJSON();
query.className = this.query.className;
var data = {};
data.query = query;
this.data = this.data || {};
this.data.source = this.data.source || currUser;
data.data = this._getDataJSON();
data.inboxType = this.inboxType || 'default';
return AVRequest('statuses', null, null, 'POST', data, options);
})
.then(response => {
this.id = response.objectId;
this.createdAt = AV._parseDate(response.createdAt);
return this;
});
} | javascript | {
"resource": ""
} | |
q29028 | train | function(objectId, options) {
if (!objectId) {
var errorObject = new AVError(
AVError.OBJECT_NOT_FOUND,
'Object not found.'
);
throw errorObject;
}
var obj = this._newObject();
obj.id = objectId;
var queryJSON = this.toJSON();
var fetchOptions = {};
if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;
if (queryJSON.include) fetchOptions.include = queryJSON.include;
if (queryJSON.includeACL)
fetchOptions.includeACL = queryJSON.includeACL;
return _request(
'classes',
this.className,
objectId,
'GET',
transformFetchOptions(fetchOptions),
options
).then(response => {
if (_.isEmpty(response))
throw new AVError(AVError.OBJECT_NOT_FOUND, 'Object not found.');
obj._finishFetch(obj.parse(response), true);
return obj;
});
} | javascript | {
"resource": ""
} | |
q29029 | train | function() {
var params = {
where: this._where,
};
if (this._include.length > 0) {
params.include = this._include.join(',');
}
if (this._select.length > 0) {
params.keys = this._select.join(',');
}
if (this._includeACL !== undefined) {
params.returnACL = this._includeACL;
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order !== undefined) {
params.order = this._order;
}
AV._objectEach(this._extraOptions, function(v, k) {
params[k] = v;
});
return params;
} | javascript | {
"resource": ""
} | |
q29030 | train | function(options) {
var self = this;
return self.find(options).then(function(objects) {
return AV.Object.destroyAll(objects, options);
});
} | javascript | {
"resource": ""
} | |
q29031 | train | function(options) {
var params = this.toJSON();
params.limit = 0;
params.count = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return response.count;
});
} | javascript | {
"resource": ""
} | |
q29032 | train | function(options) {
var self = this;
var params = this.toJSON();
params.limit = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return _.map(response.results, function(json) {
var obj = self._newObject();
if (obj._finishFetch) {
obj._finishFetch(self._processResult(json), true);
}
return obj;
})[0];
});
} | javascript | {
"resource": ""
} | |
q29033 | train | function(key, regex, modifiers) {
this._addCondition(key, '$regex', regex);
if (!modifiers) {
modifiers = '';
}
// Javascript regex options support mig as inline options but store them
// as properties of the object. We support mi & should migrate them to
// modifiers
if (regex.ignoreCase) {
modifiers += 'i';
}
if (regex.multiline) {
modifiers += 'm';
}
if (modifiers && modifiers.length) {
this._addCondition(key, '$options', modifiers);
}
return this;
} | javascript | {
"resource": ""
} | |
q29034 | train | function(key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, '$inQuery', queryJSON);
return this;
} | javascript | {
"resource": ""
} | |
q29035 | train | function(queries) {
var queryJSON = _.map(queries, function(q) {
return q.toJSON().where;
});
this._where.$and = queryJSON;
return this;
} | javascript | {
"resource": ""
} | |
q29036 | train | function(keys) {
requires(keys, 'undefined is not a valid key');
_(arguments).forEach(keys => {
this._include = this._include.concat(ensureArray(keys));
});
return this;
} | javascript | {
"resource": ""
} | |
q29037 | train | function(keys) {
requires(keys, 'undefined is not a valid key');
_(arguments).forEach(keys => {
this._select = this._select.concat(ensureArray(keys));
});
return this;
} | javascript | {
"resource": ""
} | |
q29038 | train | function() {
var self = this;
var request = this._createRequest();
return request.then(function(response) {
//update sid for next querying.
if (response.sid) {
self._oldSid = self._sid;
self._sid = response.sid;
} else {
self._sid = null;
self._hitEnd = true;
}
self._hits = response.hits || 0;
return _.map(response.results, function(json) {
if (json.className) {
response.className = json.className;
}
var obj = self._newObject(response);
obj.appURL = json['_app_url'];
obj._finishFetch(self._processResult(json), true);
return obj;
});
});
} | javascript | {
"resource": ""
} | |
q29039 | train | function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) {
return this;
}
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
event = events.shift();
while (event) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = { tail: tail, next: list ? list.next : node };
event = events.shift();
}
return this;
} | javascript | {
"resource": ""
} | |
q29040 | getValue | train | function getValue(object, prop) {
if (!(object && object[prop])) {
return null;
}
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
} | javascript | {
"resource": ""
} |
q29041 | train | function(serverData) {
// Grab a copy of any object referenced by this object. These instances
// may have already been fetched, and we don't want to lose their data.
// Note that doing it like this means we will unify separate copies of the
// same object, but that's a risk we have to take.
var fetchedObjects = {};
AV._traverse(this.attributes, function(object) {
if (object instanceof AV.Object && object.id && object._hasData) {
fetchedObjects[object.id] = object;
}
});
var savedChanges = _.first(this._opSetQueue);
this._opSetQueue = _.rest(this._opSetQueue);
this._applyOpSet(savedChanges, this._serverData);
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(value, key);
// Look for any objects that might have become unfetched and fix them
// by replacing their values with the previously observed values.
var fetched = AV._traverse(self._serverData[key], function(object) {
if (object instanceof AV.Object && fetchedObjects[object.id]) {
return fetchedObjects[object.id];
}
});
if (fetched) {
self._serverData[key] = fetched;
}
});
this._rebuildAllEstimatedData();
const opSetQueue = this._opSetQueue.map(_.clone);
this._refreshCache();
this._opSetQueue = opSetQueue;
this._saving = this._saving - 1;
} | javascript | {
"resource": ""
} | |
q29042 | train | function(serverData, hasData) {
// Clear out any changes the user might have made previously.
this._opSetQueue = [{}];
// Bring in all the new server data.
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(value, key);
});
// Refresh the attributes.
this._rebuildAllEstimatedData();
// Clear out the cache of mutable containers.
this._refreshCache();
this._opSetQueue = [{}];
this._hasData = hasData;
} | javascript | {
"resource": ""
} | |
q29043 | train | function(opSet, target) {
var self = this;
AV._objectEach(opSet, function(change, key) {
const [value, actualTarget, actualKey] = findValue(target, key);
setValue(target, key, change._estimate(value, self, key));
if (actualTarget && actualTarget[actualKey] === AV.Op._UNSET) {
delete actualTarget[actualKey];
}
});
} | javascript | {
"resource": ""
} | |
q29044 | train | function(value, attr) {
if (!self._pending[attr] && !self._silent[attr]) {
delete self.changed[attr];
}
} | javascript | {
"resource": ""
} | |
q29045 | train | function(attrs) {
if (attrs.sessionToken) {
this._sessionToken = attrs.sessionToken;
delete attrs.sessionToken;
}
return AV.User.__super__._mergeMagicFields.call(this, attrs);
} | javascript | {
"resource": ""
} | |
q29046 | train | function(provider) {
var authType;
if (_.isString(provider)) {
authType = provider;
} else {
authType = provider.getAuthType();
}
var authData = this.get('authData') || {};
return !!authData[authType];
} | javascript | {
"resource": ""
} | |
q29047 | train | function(options, authOptions) {
if (!this.id) {
throw new Error('Please signin.');
}
let user;
let attributes;
if (options.user) {
user = options.user;
attributes = options.attributes;
} else {
user = options;
}
var userObjectId = _.isString(user) ? user : user.id;
if (!userObjectId) {
throw new Error('Invalid target user.');
}
var route = 'users/' + this.id + '/friendship/' + userObjectId;
var request = AVRequest(
route,
null,
null,
'POST',
AV._encode(attributes),
authOptions
);
return request;
} | javascript | {
"resource": ""
} | |
q29048 | train | function(oldPassword, newPassword, options) {
var route = 'users/' + this.id + '/updatePassword';
var params = {
old_password: oldPassword,
new_password: newPassword,
};
var request = AVRequest(route, null, null, 'PUT', params, options);
return request;
} | javascript | {
"resource": ""
} | |
q29049 | train | function(userObjectId) {
if (!userObjectId || !_.isString(userObjectId)) {
throw new Error('Invalid user object id.');
}
var query = new AV.FriendShipQuery('_Follower');
query._friendshipTag = 'follower';
query.equalTo(
'user',
AV.Object.createWithoutData('_User', userObjectId)
);
return query;
} | javascript | {
"resource": ""
} | |
q29050 | train | function(email) {
var json = { email: email };
var request = AVRequest(
'requestPasswordReset',
null,
null,
'POST',
json
);
return request;
} | javascript | {
"resource": ""
} | |
q29051 | train | function(code, password) {
var json = { password: password };
var request = AVRequest(
'resetPasswordBySmsCode',
null,
code,
'PUT',
json
);
return request;
} | javascript | {
"resource": ""
} | |
q29052 | train | function(mobilePhoneNumber, options = {}) {
const data = {
mobilePhoneNumber,
};
if (options.validateToken) {
data.validate_token = options.validateToken;
}
var request = AVRequest(
'requestLoginSmsCode',
null,
null,
'POST',
data,
options
);
return request;
} | javascript | {
"resource": ""
} | |
q29053 | train | function() {
if (AV._config.disableCurrentUser) {
console.warn(
'AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'
);
return Promise.resolve(null);
}
if (AV.User._currentUser) {
return Promise.resolve(AV.User._currentUser);
}
if (AV.User._currentUserMatchesDisk) {
return Promise.resolve(AV.User._currentUser);
}
return AV.localStorage
.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY))
.then(function(userData) {
if (!userData) {
return null;
}
// Load the user from local storage.
AV.User._currentUserMatchesDisk = true;
AV.User._currentUser = AV.Object._create('_User');
AV.User._currentUser._isCurrentUser = true;
var json = JSON.parse(userData);
AV.User._currentUser.id = json._id;
delete json._id;
AV.User._currentUser._sessionToken = json._sessionToken;
delete json._sessionToken;
AV.User._currentUser._finishFetch(json);
//AV.User._currentUser.set(json);
AV.User._currentUser._synchronizeAllAuthData();
AV.User._currentUser._refreshCache();
AV.User._currentUser._opSetQueue = [{}];
return AV.User._currentUser;
});
} | javascript | {
"resource": ""
} | |
q29054 | train | function() {
AV.GeoPoint._validate(this.latitude, this.longitude);
return {
__type: 'GeoPoint',
latitude: this.latitude,
longitude: this.longitude,
};
} | javascript | {
"resource": ""
} | |
q29055 | getNextSearchDir | train | function getNextSearchDir( ptA, ptB, dir ){
var ABdotB = ptB.normSq() - ptB.dot( ptA )
,ABdotA = ptB.dot( ptA ) - ptA.normSq()
;
// if the origin is farther than either of these points
// get the direction from one of those points to the origin
if ( ABdotB < 0 ){
return dir.clone( ptB ).negate();
} else if ( ABdotA > 0 ){
return dir.clone( ptA ).negate();
// otherwise, use the perpendicular direction from the simplex
} else {
// dir = AB = B - A
dir.clone( ptB ).vsub( ptA );
// if (left handed coordinate system)
// A cross AB < 0 then get perpendicular counterclockwise
return dir.perp( (ptA.cross( dir ) > 0) );
}
} | javascript | {
"resource": ""
} |
q29056 | Transform | train | function Transform( vect, angle, origin ) {
if (!(this instanceof Transform)){
return new Transform( vect, angle );
}
this.v = new Physics.vector();
this.o = new Physics.vector(); // origin of rotation
if ( vect instanceof Transform ){
this.clone( vect );
return;
}
if (vect){
this.setTranslation( vect );
}
this.setRotation( angle || 0, origin );
} | javascript | {
"resource": ""
} |
q29057 | wrapDefine | train | function wrapDefine( src, path ){
path = path.replace('src/', '');
var deps = ['physicsjs'];
var l = path.split('/').length;
var pfx = l > 0 ? (new Array( l )).join('../') : './';
src.replace(/@requires\s([\w-_\/]+(\.js)?)/g, function( match, dep ){
var i = dep.indexOf('.js');
if ( i > -1 ){
// must be a 3rd party dep
dep = dep.substr( 0, i );
deps.push( dep );
} else {
// just get the dependency
deps.push( pfx + dep );
}
// no effect
return match;
});
var data = {
src: src.replace(/\n/g, '\n '),
path: path,
deps: deps
};
return grunt.template.process(config.banner, config) +
grunt.template.process(config.extensionWrapper, {data: data});
} | javascript | {
"resource": ""
} |
q29058 | ConnectionTimeoutError | train | function ConnectionTimeoutError(timeout) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.message = 'connection timed out';
if (timeout) {
this.message += '. timeout = ' + timeout + ' ms';
}
this.name = 'ConnectionTimeoutError';
} | javascript | {
"resource": ""
} |
q29059 | ImapSimple | train | function ImapSimple(imap) {
var self = this;
self.imap = imap;
// flag to determine whether we should suppress ECONNRESET from bubbling up to listener
self.ending = false;
// pass most node-imap `Connection` events through 1:1
['alert', 'mail', 'expunge', 'uidvalidity', 'update', 'close', 'end'].forEach(function (event) {
self.imap.on(event, self.emit.bind(self, event));
});
// special handling for `error` event
self.imap.on('error', function (err) {
// if .end() has been called and an 'ECONNRESET' error is received, don't bubble
if (err && self.ending && (err.code.toUpperCase() === 'ECONNRESET')) {
return;
}
self.emit('error', err);
});
} | javascript | {
"resource": ""
} |
q29060 | connect | train | function connect(options, callback) {
options = options || {};
options.imap = options.imap || {};
// support old connectTimeout config option. Remove in v2.0.0
if (options.hasOwnProperty('connectTimeout')) {
console.warn('[imap-simple] connect: options.connectTimeout is deprecated. ' +
'Please use options.imap.authTimeout instead.');
options.imap.authTimeout = options.connectTimeout;
}
// set default authTimeout
options.imap.authTimeout = options.imap.hasOwnProperty('authTimeout') ? options.imap.authTimeout : 2000;
if (callback) {
return nodeify(connect(options), callback);
}
return new Promise(function (resolve, reject) {
var imap = new Imap(options.imap);
function imapOnReady() {
imap.removeListener('error', imapOnError);
imap.removeListener('close', imapOnClose);
imap.removeListener('end', imapOnEnd);
resolve(new ImapSimple(imap));
}
function imapOnError(err) {
if (err.source === 'timeout-auth') {
err = new errors.ConnectionTimeoutError(options.imap.authTimeout);
}
imap.removeListener('ready', imapOnReady);
imap.removeListener('close', imapOnClose);
imap.removeListener('end', imapOnEnd);
reject(err);
}
function imapOnEnd() {
imap.removeListener('ready', imapOnReady);
imap.removeListener('error', imapOnError);
imap.removeListener('close', imapOnClose);
reject(new Error('Connection ended unexpectedly'));
}
function imapOnClose() {
imap.removeListener('ready', imapOnReady);
imap.removeListener('error', imapOnError);
imap.removeListener('end', imapOnEnd);
reject(new Error('Connection closed unexpectedly'));
}
imap.once('ready', imapOnReady);
imap.once('error', imapOnError);
imap.once('close', imapOnClose);
imap.once('end', imapOnEnd);
if (options.hasOwnProperty('onmail')) {
imap.on('mail', options.onmail);
}
if (options.hasOwnProperty('onexpunge')) {
imap.on('expunge', options.onexpunge);
}
if (options.hasOwnProperty('onupdate')) {
imap.on('update', options.onupdate);
}
imap.connect();
});
} | javascript | {
"resource": ""
} |
q29061 | getParts | train | function getParts(struct, parts) {
parts = parts || [];
for (var i = 0; i < struct.length; i++) {
if (Array.isArray(struct[i])) {
getParts(struct[i], parts);
} else if (struct[i].partID) {
parts.push(struct[i]);
}
}
return parts;
} | javascript | {
"resource": ""
} |
q29062 | random | train | function random(array, len) {
const size = array.length;
const randomIndexes = crypto.randomBytes(len).toJSON().data;
return randomIndexes.map((char) => array[char % size]).join('');
} | javascript | {
"resource": ""
} |
q29063 | ruleIsMatch | train | function ruleIsMatch(host, port) {
const { host: rHost, port: rPort } = this;
const slashIndex = rHost.indexOf('/');
let isHostMatch = false;
if (slashIndex !== -1 && net.isIP(host)) {
isHostMatch = ip.cidrSubnet(rHost).contains(host);
} else {
isHostMatch = (rHost === host);
}
if (rHost === '*' || isHostMatch) {
if (rPort === '*' || port === rPort) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q29064 | getHostType | train | function getHostType(host) {
if (net.isIPv4(host)) {
return ATYP_V4;
}
if (net.isIPv6(host)) {
return ATYP_V6;
}
return ATYP_DOMAIN;
} | javascript | {
"resource": ""
} |
q29065 | obtainConfig | train | function obtainConfig(file) {
let json;
try {
const jsonFile = fs.readFileSync(file);
json = JSON.parse(jsonFile);
} catch (err) {
throw Error(`fail to load/parse your '${file}': ${err.message}`);
}
return json;
} | javascript | {
"resource": ""
} |
q29066 | ApplicationData | train | function ApplicationData(buffer) {
const len = numberToBuffer(buffer.length);
return Buffer.concat([stb('170303'), len, buffer]);
} | javascript | {
"resource": ""
} |
q29067 | train | function() {
var err = null, status = parseInt(res.statusCode, 10);
if (status > 399) { // Unsuccessful HTTP status? Then pass an error to the callback
var match = data.match(/^\{"message": "(.+)"\}/i);
err = new error.DiscogsError(status, ((match && match[1]) ? match[1] : null));
}
callback(err, data, rateLimit);
} | javascript | {
"resource": ""
} | |
q29068 | DiscogsError | train | function DiscogsError(statusCode, message){
Error.captureStackTrace(this, this.constructor);
this.statusCode = statusCode||404;
this.message = message||'Unknown error.';
} | javascript | {
"resource": ""
} |
q29069 | calculateSourceAnchor | train | function calculateSourceAnchor (source, startTime) {
if (startTime === undefined || isNaN(startTime)) {
return source;
}
if (windowType === WindowTypes.STATIC) {
return startTime === 0 ? source : source + '#t=' + parseInt(startTime);
}
if (windowType === WindowTypes.SLIDING) {
return startTime === 0 ? source : source + '#r=' + parseInt(startTime);
}
if (windowType === WindowTypes.GROWING) {
var windowStartTimeSeconds = (timeData.windowStartTime / 1000);
var srcWithTimeAnchor = source + '#t=';
startTime = parseInt(startTime);
return startTime === 0 ? srcWithTimeAnchor + (windowStartTimeSeconds + 1) : srcWithTimeAnchor + (windowStartTimeSeconds + startTime);
}
} | javascript | {
"resource": ""
} |
q29070 | toggleControls | train | function toggleControls () {
controlsElement.style.display = controlsElement.style.display == "none" ? "block" : "none";
if (controlsElement.style.display === "block") {
playButton.focus();
}
} | javascript | {
"resource": ""
} |
q29071 | startControlsTimeOut | train | function startControlsTimeOut () {
clearTimeout(controlsTimeout);
if (controlsElement.style.display === "block") {
controlsTimeout = setTimeout(function () {
toggleControls();
}, 5000);
} else {
toggleControls();
}
} | javascript | {
"resource": ""
} |
q29072 | setupControls | train | function setupControls () {
window.addEventListener('keydown', function () {
startControlsTimeOut();
});
playButton.addEventListener('click', function () {
bigscreenPlayer.play();
startControlsTimeOut();
});
pauseButton.addEventListener('click', function () {
bigscreenPlayer.pause();
startControlsTimeOut();
});
seekForwardButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getCurrentTime() + 10);
startControlsTimeOut();
});
seekBackButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getCurrentTime() - 10);
startControlsTimeOut();
});
seekToEndButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getDuration() - 10);
startControlsTimeOut();
});
debugToolButton.addEventListener('click', function () {
DebugTool.toggleVisibility();
startControlsTimeOut();
});
bigscreenPlayer.registerForTimeUpdates(function (event) {
});
bigscreenPlayer.registerForStateChanges(function (event) {
var state = 'EMPTY';
switch (event.state) {
case 0: state = 'STOPPED'; break;
case 1: state = 'PAUSED'; break;
case 2: state = 'PLAYING'; break;
case 4: state = 'WAITING'; break;
case 5: state = 'ENDED'; break;
case 6: state = 'FATAL_ERROR'; break;
}
if (state === 'WAITING') {
playbackElement.appendChild(playbackSpinner);
} else {
playbackElement.removeChild(playbackSpinner);
}
});
} | javascript | {
"resource": ""
} |
q29073 | isNearToCurrentTime | train | function isNearToCurrentTime (seconds) {
var currentTime = getCurrentTime();
var targetTime = getClampedTime(seconds);
return Math.abs(currentTime - targetTime) <= CURRENT_TIME_TOLERANCE;
} | javascript | {
"resource": ""
} |
q29074 | getClampedTime | train | function getClampedTime (seconds) {
var range = getSeekableRange();
var offsetFromEnd = getClampOffsetFromConfig();
var nearToEnd = Math.max(range.end - offsetFromEnd, range.start);
if (seconds < range.start) {
return range.start;
} else if (seconds > nearToEnd) {
return nearToEnd;
} else {
return seconds;
}
} | javascript | {
"resource": ""
} |
q29075 | train | function (skyType, sunHeight) {
var fogColor;
if (skyType == 'color' || skyType == 'none'){
fogColor = new THREE.Color(this.data.skyColor);
}
else if (skyType == 'gradient'){
fogColor = new THREE.Color(this.data.horizonColor);
}
else if (skyType == 'atmosphere')
{
var fogRatios = [ 1, 0.5, 0.22, 0.1, 0.05, 0];
var fogColors = ['#C0CDCF', '#81ADC5', '#525e62', '#2a2d2d', '#141616', '#000'];
if (sunHeight <= 0) return '#000';
sunHeight = Math.min(1, sunHeight);
for (var i = 0; i < fogRatios.length; i++){
if (sunHeight > fogRatios[i]){
var c1 = new THREE.Color(fogColors[i - 1]);
var c2 = new THREE.Color(fogColors[i]);
var a = (sunHeight - fogRatios[i]) / (fogRatios[i - 1] - fogRatios[i]);
c2.lerp(c1, a);
fogColor = c2;
break;
}
}
}
// dim down the color
fogColor.multiplyScalar(0.9);
// mix it a bit with ground color
fogColor.lerp(new THREE.Color(this.data.groundColor), 0.3);
return '#' + fogColor.getHexString();
} | javascript | {
"resource": ""
} | |
q29076 | train | function () {
var str = '{';
for (var i in this.schema){
if (i == 'preset') continue;
str += i + ': ';
var type = this.schema[i].type;
if (type == 'vec3') {
str += '{ x: ' + this.data[i].x + ', y: ' + this.data[i].y + ', z: ' + this.data[i].z + '}';
}
else if (type == 'string' || type == 'color') {
str += '"' + this.data[i] + '"';
}
else {
str += this.data[i];
}
str += ', ';
}
str += '}';
console.log(str);
} | javascript | {
"resource": ""
} | |
q29077 | train | function () {
// trim number to 3 decimals
function dec3 (v) {
return Math.floor(v * 1000) / 1000;
}
var params = [];
var usingPreset = this.data.preset != 'none' ? this.presets[this.data.preset] : false;
if (usingPreset) {
params.push('preset: ' + this.data.preset);
}
for (var i in this.schema) {
if (i == 'preset' || (usingPreset && usingPreset[i] === undefined)) {
continue;
}
var def = usingPreset ? usingPreset[i] : this.schema[i].default;
var data = this.data[i];
var type = this.schema[i].type;
if (type == 'vec3') {
var coords = def;
if (typeof(def) == 'string') {
def = def.split(' ');
coords = {x: def[0], y: def[1], z: def[2]};
}
if (dec3(coords.x) != dec3(data.x) || dec3(coords.y) != dec3(data.y) || dec3(coords.z) != dec3(data.z)) {
params.push(i + ': ' + dec3(data.x) + ' ' + dec3(data.y) + ' ' + dec3(data.z));
}
}
else {
if (def != data) {
if (this.schema[i].type == 'number') {
data = dec3(data);
}
params.push(i + ': ' + data);
}
}
}
console.log('%c' + params.join('; '), 'color: #f48;font-weight:bold');
} | javascript | {
"resource": ""
} | |
q29078 | train | function (ctx, size, texMeters) {
if (this.data.grid == 'none') return;
// one grid feature each 2 meters
var num = Math.floor(texMeters / 2);
var step = size / (texMeters / 2); // 2 meters == <step> pixels
var i, j, ii;
ctx.fillStyle = this.data.gridColor;
switch (this.data.grid) {
case '1x1':
case '2x2': {
if (this.data.grid == '1x1') {
num = num * 2;
step = size / texMeters;
}
for (i = 0; i < num; i++) {
ii = Math.floor(i * step);
ctx.fillRect(0, ii, size, 1);
ctx.fillRect(ii, 0, 1, size);
}
break;
}
case 'crosses': {
var l = Math.floor(step / 20);
for (i = 0; i < num + 1; i++) {
ii = Math.floor(i * step);
for (j = 0; j < num + 1; j++) {
var jj = Math.floor(-l + j * step);
ctx.fillRect(jj, ii, l * 2, 1);
ctx.fillRect(ii, jj, 1, l * 2);
}
}
break;
}
case 'dots': {
for (i = 0; i < num + 1; i++) {
for (j = 0; j < num + 1; j++) {
ctx.beginPath(); ctx.arc(Math.floor(j * step), Math.floor(i * step), 4, 0, Math.PI * 2); ctx.fill();
}
}
break;
}
case 'xlines': {
for (i = 0; i < num; i++) {
ctx.fillRect(Math.floor(i * step), 0, 1, size);
}
break;
}
case 'ylines': {
for (i = 0; i < num; i++) {
ctx.fillRect(0, Math.floor(i * step), size, 1);
}
break;
}
}
} | javascript | {
"resource": ""
} | |
q29079 | train | function() {
var numStars = 2000;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array( numStars * 3 );
var radius = this.STAGE_SIZE - 1;
var v = new THREE.Vector3();
for (var i = 0; i < positions.length; i += 3) {
v.set(this.random(i + 23) - 0.5, this.random(i + 24), this.random(i + 25) - 0.5);
v.normalize();
v.multiplyScalar(radius);
positions[i ] = v.x;
positions[i+1] = v.y;
positions[i+2] = v.z;
}
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setDrawRange(0, 0); // don't draw any yet
var material = new THREE.PointsMaterial({size: 0.01, color: 0xCCCCCC, fog: false});
this.stars.setObject3D('mesh', new THREE.Points(geometry, material));
} | javascript | {
"resource": ""
} | |
q29080 | checkIfExists | train | function checkIfExists () {
// Create after we check for pre-sleep .dat stuff
var createAfterValid = (createIfMissing && !errorIfExists)
var missingError = new Error('Dat storage does not exist.')
missingError.name = 'MissingError'
var existsError = new Error('Dat storage already exists.')
existsError.name = 'ExistsError'
var oldError = new Error('Dat folder contains incompatible metadata. Please remove your metadata (rm -rf .dat).')
oldError.name = 'IncompatibleError'
fs.readdir(path.join(opts.dir, '.dat'), function (err, files) {
// TODO: omg please make this less confusing.
var noDat = !!(err || !files.length)
hasDat = !noDat
var validSleep = (files && files.length && files.indexOf('metadata.key') > -1)
var badDat = !(noDat || validSleep)
if ((noDat || validSleep) && createAfterValid) return create()
else if (badDat) return cb(oldError)
if (err && !createIfMissing) return cb(missingError)
else if (!err && errorIfExists) return cb(existsError)
return create()
})
} | javascript | {
"resource": ""
} |
q29081 | defaultStorage | train | function defaultStorage (storage, opts) {
// Use custom storage or ram
if (typeof storage !== 'string') return storage
if (opts.temp) return ram
if (opts.latest === false) {
// Store as SLEEP files inluding content.data
return {
metadata: function (name, opts) {
// I don't think we want this, we may get multiple 'ogd' sources
// if (name === 'secret_key') return secretStorage()(path.join(storage, 'metadata.ogd'), {key: opts.key, discoveryKey: opts.discoveryKey})
return raf(path.join(storage, 'metadata.' + name))
},
content: function (name, opts) {
return raf(path.join(storage, 'content.' + name))
}
}
}
try {
// Store in .dat with secret in ~/.dat
if (fs.statSync(storage).isDirectory()) {
return datStore(storage, opts)
}
} catch (e) {
// Does not exist, make dir
try {
fs.mkdirSync(storage)
} catch (e) {
// Invalid path
throw new Error('Invalid storage path')
}
return datStore(storage, opts)
}
error()
function error () {
// TODO: single file sleep storage
throw new Error('Storage must be dir or opts.temp')
}
} | javascript | {
"resource": ""
} |
q29082 | polygonClosed | train | function polygonClosed(coordinates) {
var a = coordinates[0],
b = coordinates[coordinates.length - 1];
return !(a[0] - b[0] || a[1] - b[1]);
} | javascript | {
"resource": ""
} |
q29083 | train | function (data){
// set data
if (!arguments.length) {
if (scope.options.chart.type === 'sunburstChart') {
data = angular.copy(scope.data);
} else {
data = scope.data;
}
} else {
scope.data = data;
// return if data $watch is enabled
if (scope._config.deepWatchData && !scope._config.disabled) return;
}
if (data) {
// remove whole svg element with old data
d3.select(element[0]).select('svg').remove();
var h, w;
// Select the current element to add <svg> element and to render the chart in
scope.svg = d3.select(element[0]).insert('svg', '.caption');
if (h = scope.options.chart.height) {
if (!isNaN(+h)) h += 'px'; //check if height is number
scope.svg.attr('height', h).style({height: h});
}
if (w = scope.options.chart.width) {
if (!isNaN(+w)) w += 'px'; //check if width is number
scope.svg.attr('width', w).style({width: w});
} else {
scope.svg.attr('width', '100%').style({width: '100%'});
}
scope.svg.datum(data).call(scope.chart);
// update zooming if exists
if (scope.chart && scope.chart.zoomRender) scope.chart.zoomRender();
}
} | javascript | {
"resource": ""
} | |
q29084 | train | function (){
element.find('.title').remove();
element.find('.subtitle').remove();
element.find('.caption').remove();
element.empty();
// remove tooltip if exists
if (scope.chart && scope.chart.tooltip && scope.chart.tooltip.id) {
d3.select('#' + scope.chart.tooltip.id()).remove();
}
// To be compatible with old nvd3 (v1.7.1)
if (nv.graphs && scope.chart) {
for (var i = nv.graphs.length - 1; i >= 0; i--) {
if (nv.graphs[i] && (nv.graphs[i].id === scope.chart.id)) {
nv.graphs.splice(i, 1);
}
}
}
if (nv.tooltip && nv.tooltip.cleanup) {
nv.tooltip.cleanup();
}
if (scope.chart && scope.chart.resizeHandler) scope.chart.resizeHandler.clear();
scope.chart = null;
} | javascript | {
"resource": ""
} | |
q29085 | configure | train | function configure(chart, options, chartType){
if (chart && options){
angular.forEach(chart, function(value, key){
if (key[0] === '_');
else if (key === 'dispatch') {
if (options[key] === undefined || options[key] === null) {
if (scope._config.extended) options[key] = {};
}
configureEvents(value, options[key]);
}
else if (key === 'tooltip') {
if (options[key] === undefined || options[key] === null) {
if (scope._config.extended) options[key] = {};
}
configure(chart[key], options[key], chartType);
}
else if (key === 'contentGenerator') {
if (options[key]) chart[key](options[key]);
}
else if ([
'axis',
'clearHighlights',
'defined',
'highlightPoint',
'nvPointerEventsClass',
'options',
'rangeBand',
'rangeBands',
'scatter',
'open',
'close',
'node'
].indexOf(key) === -1) {
if (options[key] === undefined || options[key] === null){
if (scope._config.extended) options[key] = value();
}
else chart[key](options[key]);
}
});
}
} | javascript | {
"resource": ""
} |
q29086 | configureWrapper | train | function configureWrapper(name){
var _ = nvd3Utils.deepExtend(defaultWrapper(name), scope.options[name] || {});
if (scope._config.extended) scope.options[name] = _;
var wrapElement = angular.element('<div></div>').html(_['html'] || '')
.addClass(name).addClass(_.className)
.removeAttr('style')
.css(_.css);
if (!_['html']) wrapElement.text(_.text);
if (_.enable) {
if (name === 'title') element.prepend(wrapElement);
else if (name === 'subtitle') angular.element(element[0].querySelector('.title')).after(wrapElement);
else if (name === 'caption') element.append(wrapElement);
}
} | javascript | {
"resource": ""
} |
q29087 | configureStyles | train | function configureStyles(){
var _ = nvd3Utils.deepExtend(defaultStyles(), scope.options['styles'] || {});
if (scope._config.extended) scope.options['styles'] = _;
angular.forEach(_.classes, function(value, key){
value ? element.addClass(key) : element.removeClass(key);
});
element.removeAttr('style').css(_.css);
} | javascript | {
"resource": ""
} |
q29088 | defaultWrapper | train | function defaultWrapper(_){
switch (_){
case 'title': return {
enable: false,
text: 'Write Your Title',
className: 'h4',
css: {
width: scope.options.chart.width + 'px',
textAlign: 'center'
}
};
case 'subtitle': return {
enable: false,
text: 'Write Your Subtitle',
css: {
width: scope.options.chart.width + 'px',
textAlign: 'center'
}
};
case 'caption': return {
enable: false,
text: 'Figure 1. Write Your Caption text.',
css: {
width: scope.options.chart.width + 'px',
textAlign: 'center'
}
};
}
} | javascript | {
"resource": ""
} |
q29089 | dataWatchFn | train | function dataWatchFn(newData, oldData) {
if (newData !== oldData){
if (!scope._config.disabled) {
scope._config.refreshDataOnly ? scope.api.update() : scope.api.refresh(); // if wanted to refresh data only, use update method, otherwise use full refresh.
}
}
} | javascript | {
"resource": ""
} |
q29090 | FileKeyInfo | train | function FileKeyInfo(file) {
this.file = file
this.getKeyInfo = function(key, prefix) {
prefix = prefix || ''
prefix = prefix ? prefix + ':' : prefix
return "<" + prefix + "X509Data></" + prefix + "X509Data>"
}
this.getKey = function(keyInfo) {
return fs.readFileSync(this.file)
}
} | javascript | {
"resource": ""
} |
q29091 | RSASHA512 | train | function RSASHA512() {
/**
* Sign the given string using the given key
*
*/
this.getSignature = function(signedInfo, signingKey) {
var signer = crypto.createSign("RSA-SHA512")
signer.update(signedInfo)
var res = signer.sign(signingKey, 'base64')
return res
}
/**
* Verify the given signature of the given string using key
*
*/
this.verifySignature = function(str, key, signatureValue) {
var verifier = crypto.createVerify("RSA-SHA512")
verifier.update(str)
var res = verifier.verify(key, signatureValue, 'base64')
return res
}
this.getAlgorithmName = function() {
return "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
}
} | javascript | {
"resource": ""
} |
q29092 | findAncestorNs | train | function findAncestorNs(doc, docSubsetXpath){
var docSubset = xpath.select(docSubsetXpath, doc);
if(!Array.isArray(docSubset) || docSubset.length < 1){
return [];
}
// Remove duplicate on ancestor namespace
var ancestorNs = collectAncestorNamespaces(docSubset[0]);
var ancestorNsWithoutDuplicate = [];
for(var i=0;i<ancestorNs.length;i++){
var notOnTheList = true;
for(var v in ancestorNsWithoutDuplicate){
if(ancestorNsWithoutDuplicate[v].prefix === ancestorNs[i].prefix){
notOnTheList = false;
break;
}
}
if(notOnTheList){
ancestorNsWithoutDuplicate.push(ancestorNs[i]);
}
}
// Remove namespaces which are already declared in the subset with the same prefix
var returningNs = [];
var subsetAttributes = docSubset[0].attributes;
for(var j=0;j<ancestorNsWithoutDuplicate.length;j++){
var isUnique = true;
for(var k=0;k<subsetAttributes.length;k++){
var nodeName = subsetAttributes[k].nodeName;
if(nodeName.search(/^xmlns:/) === -1) continue;
var prefix = nodeName.replace(/^xmlns:/, "");
if(ancestorNsWithoutDuplicate[j].prefix === prefix){
isUnique = false;
break;
}
}
if(isUnique){
returningNs.push(ancestorNsWithoutDuplicate[j]);
}
}
return returningNs;
} | javascript | {
"resource": ""
} |
q29093 | SignedXml | train | function SignedXml(idMode, options) {
this.options = options || {};
this.idMode = idMode
this.references = []
this.id = 0
this.signingKey = null
this.signatureAlgorithm = this.options.signatureAlgorithm || "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
this.keyInfoProvider = null
this.canonicalizationAlgorithm = this.options.canonicalizationAlgorithm || "http://www.w3.org/2001/10/xml-exc-c14n#"
this.signedXml = ""
this.signatureXml = ""
this.signatureNode = null
this.signatureValue = ""
this.originalXmlWithIds = ""
this.validationErrors = []
this.keyInfo = null
this.idAttributes = [ 'Id', 'ID', 'id' ];
if (this.options.idAttribute) this.idAttributes.splice(0, 0, this.options.idAttribute);
this.implicitTransforms = this.options.implicitTransforms || [];
} | javascript | {
"resource": ""
} |
q29094 | wrap | train | function wrap(text, width, wrapSplitter) {
var lineHeight = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1.2;
text.each(function () {
var text = select(this),
words = text.text().split(wrapSplitter || /[ \t\r\n]+/).reverse().filter(function (w) {
return w !== "";
});
var word = void 0,
line$$1 = [],
tspan = text.text(null).append("tspan").attr("x", 0).attr("dy", 0.8 + "em");
while (word = words.pop()) {
line$$1.push(word);
tspan.text(line$$1.join(" "));
if (tspan.node().getComputedTextLength() > width && line$$1.length > 1) {
line$$1.pop();
tspan.text(line$$1.join(" "));
line$$1 = [word];
tspan = text.append("tspan").attr("x", 0).attr("dy", lineHeight + "em").text(word);
}
}
});
} | javascript | {
"resource": ""
} |
q29095 | JstdPlugin | train | function JstdPlugin() {
var nop = function() {};
this.reportResult = nop;
this.reportEnd = nop;
this.runScenario = nop;
this.name = 'Angular Scenario Adapter';
/**
* Called for each JSTD TestCase
*
* Handles only SCENARIO_TYPE test cases. There should be only one fake TestCase.
* Runs all scenario tests (under one fake TestCase) and report all results to JSTD.
*
* @param {jstestdriver.TestRunConfiguration} configuration
* @param {Function} onTestDone
* @param {Function} onAllTestsComplete
* @returns {boolean} True if this type of test is handled by this plugin, false otherwise
*/
this.runTestConfiguration = function(configuration, onTestDone, onAllTestsComplete) {
if (configuration.getTestCaseInfo().getType() != SCENARIO_TYPE) return false;
this.reportResult = onTestDone;
this.reportEnd = onAllTestsComplete;
this.runScenario();
return true;
};
this.getTestRunsConfigurationFor = function(testCaseInfos, expressions, testRunsConfiguration) {
testRunsConfiguration.push(
new jstestdriver.TestRunConfiguration(
new jstestdriver.TestCaseInfo(
'Angular Scenario Tests', function() {}, SCENARIO_TYPE), []));
return true;
};
} | javascript | {
"resource": ""
} |
q29096 | css_defaultDisplay | train | function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
} | javascript | {
"resource": ""
} |
q29097 | actualDisplay | train | function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
} | javascript | {
"resource": ""
} |
q29098 | train | function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
} | javascript | {
"resource": ""
} | |
q29099 | benchmark | train | function benchmark(fn, times, name){
fn = fn.toString();
var s = fn.indexOf('{')+1,
e = fn.lastIndexOf('}');
fn = fn.substring(s,e);
return benchmarkString(fn, times, name);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.