_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q700 | rename | train | function rename(source, destination) {
const parent = path.dirname(destination);
if (exists(destination)) {
if (isDirectory(destination)) {
destination = path.join(destination, path.basename(source));
} else {
if (isDirectory(source)) {
throw new Error(`Cannot rename directory ${source} into existing file ${destination}`);
}
}
} else if (!exists(parent)) {
mkdir(parent);
}
try {
fs.renameSync(source, destination);
} catch (e) {
if (e.code !== 'EXDEV') throw e;
// Fallback for moving across devices
copy(source, destination);
fileDelete(source);
}
} | javascript | {
"resource": ""
} |
q701 | getBlock | train | function getBlock(type) {
switch (type) {
case 'Radio':
case 'Bool':
return Radio;
case 'Checkbox':
return Checkbox;
case 'Number':
return Number;
case 'Select':
return Select;
case 'Image':
return Image;
case 'Text':
return Text;
case 'Input':
return Input;
case 'Textarea':
return Textarea;
case 'Data':
return Data;
case 'Evaluation':
return Evaluation;
case 'FetchOrg':
return FetchOrg;
case 'Table':
return Table;
case 'Signature':
return Signature;
case 'Summary':
return Summary;
case 'Sum':
return Sum;
case 'Switch':
return Switch;
case 'Information':
return Information;
default:
return null;
}
} | javascript | {
"resource": ""
} |
q702 | iniFileGet | train | function iniFileGet(file, section, key, options) {
options = _.sanitize(options, {encoding: 'utf-8', default: ''});
if (!exists(file)) {
return '';
} else if (!isFile(file)) {
throw new Error(`File '${file}' is not a file`);
}
const config = ini.parse(read(file, _.pick(options, 'encoding')));
let value;
if (section in config) {
value = config[section][key];
} else if (_.isEmpty(section)) {
// global section
value = config[key];
}
return _.isUndefined(value) ? options.default : value;
} | javascript | {
"resource": ""
} |
q703 | sleep | train | function sleep(seconds) {
const time = parseFloat(seconds, 10);
if (!_.isFinite(time)) { throw new Error(`invalid time interval '${seconds}'`); }
runProgram('sleep', [time], {logCommand: false});
} | javascript | {
"resource": ""
} |
q704 | ApiError | train | function ApiError(type, message, data) {
this.name = 'ApiError';
this.type = type;
this.message = message;
this.data = data;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
} | javascript | {
"resource": ""
} |
q705 | stripPathElements | train | function stripPathElements(filePath, nelements, from) {
if (!nelements || nelements <= 0) return filePath;
from = from || 'start';
filePath = filePath.replace(/\/+$/, '');
let splitPath = split(filePath);
if (from === 'start' && path.isAbsolute(filePath) && splitPath[0] === '/') splitPath = splitPath.slice(1);
let start = 0;
let end = splitPath.length;
if (from === 'start') {
start = nelements;
end = splitPath.length;
} else {
start = 0;
end = splitPath.length - nelements;
}
return join(splitPath.slice(start, end));
} | javascript | {
"resource": ""
} |
q706 | listDirContents | train | function listDirContents(prefix, options) {
prefix = path.resolve(prefix);
options = _.sanitize(options, {stripPrefix: false, includeTopDir: false, compact: true, getAllAttrs: false,
include: ['*'], exclude: [], onlyFiles: false, rootDir: null, prefix: null, followSymLinks: false,
listSymLinks: true});
const results = [];
// TODO: prefix is an alias to rootDir. Remove it
const root = options.rootDir || options.prefix || prefix;
walkDir(prefix, (file, data) => {
if (!matches(file, options.include, options.exclude)) return;
if (data.type === 'directory' && options.onlyFiles) return;
if (data.type === 'link' && !options.listSymLinks) return;
if (data.topDir && !options.includeTopDir) return;
const filename = options.stripPrefix ? data.file : file;
if (options.compact) {
results.push(filename);
} else {
let fileInfo = {file: filename, type: data.type};
if (options.getAllAttrs) {
fileInfo = _getFileMetadata(file, fileInfo);
fileInfo.srcPath = file;
}
results.push(fileInfo);
}
}, {prefix: root});
return results;
} | javascript | {
"resource": ""
} |
q707 | getOwnerAndGroup | train | function getOwnerAndGroup(file) {
const data = fs.lstatSync(file);
const groupname = getGroupname(data.gid, {throwIfNotFound: false}) || null;
const username = getUsername(data.uid, {throwIfNotFound: false}) || null;
return {uid: data.uid, gid: data.gid, username: username, groupname: groupname};
} | javascript | {
"resource": ""
} |
q708 | _chown | train | function _chown(file, uid, gid, options) {
options = _.opts(options, {abortOnError: true});
uid = parseInt(uid, 10);
uid = _.isFinite(uid) ? uid : getUid(_fileStats(file).uid, {refresh: false});
gid = parseInt(gid, 10);
gid = _.isFinite(gid) ? gid : getGid(_fileStats(file).gid, {refresh: false});
try {
if (options.abortOnError) {
nodeFs.chownSync(file, uid, gid);
} else {
fs.chownSync(file, uid, gid);
}
} catch (e) {
if (options.abortOnError) {
throw e;
}
}
} | javascript | {
"resource": ""
} |
q709 | chown | train | function chown(file, uid, gid, options) {
if (!isPlatform('unix')) return;
if (_.isObject(uid)) {
options = gid;
const ownerInfo = uid;
uid = (ownerInfo.uid || ownerInfo.owner || ownerInfo.user || ownerInfo.username);
gid = (ownerInfo.gid || ownerInfo.group);
}
options = _.sanitize(options, {abortOnError: true, recursive: false});
let recurse = false;
try {
if (uid) uid = getUid(uid, {refresh: false});
if (gid) gid = getGid(gid, {refresh: false});
if (!exists(file)) throw new Error(`Path '${file}' does not exists`);
recurse = options.recursive && isDirectory(file);
} catch (e) {
if (options.abortOnError) {
throw e;
} else {
return;
}
}
if (recurse) {
_.each(listDirContents(file, {includeTopDir: true}), function(f) {
_chown(f, uid, gid, options);
});
} else {
_chown(file, uid, gid, options);
}
} | javascript | {
"resource": ""
} |
q710 | isPortInUse | train | function isPortInUse(port) {
_validatePortFormat(port);
if (isPlatform('unix')) {
if (isPlatform('linux') && fileExists('/proc/net')) {
return _isPortInUseRaw(port);
} else if (isInPath('netstat')) {
return _isPortInUseNetstat(port);
} else {
throw new Error('Cannot check port status');
}
} else {
throw new Error('Port checking not supported on this platform');
}
} | javascript | {
"resource": ""
} |
q711 | load | train | function load(schema) {
var obj;
if (typeof schema == 'string' && schema !== 'null') {
// This last predicate is to allow `avro.parse('null')` to work similarly
// to `avro.parse('int')` and other primitives (null needs to be handled
// separately since it is also a valid JSON identifier).
try {
obj = JSON.parse(schema);
} catch (err) {
if (~schema.indexOf('/')) {
// This can't be a valid name, so we interpret is as a filepath. This
// makes is always feasible to read a file, independent of its name
// (i.e. even if its name is valid JSON), by prefixing it with `./`.
obj = JSON.parse(fs.readFileSync(schema));
}
}
}
if (obj === undefined) {
obj = schema;
}
return obj;
} | javascript | {
"resource": ""
} |
q712 | createImportHook | train | function createImportHook() {
var imports = {};
return function (fpath, kind, cb) {
if (imports[fpath]) {
// Already imported, return nothing to avoid duplicating attributes.
process.nextTick(cb);
return;
}
imports[fpath] = true;
fs.readFile(fpath, {encoding: 'utf8'}, cb);
};
} | javascript | {
"resource": ""
} |
q713 | pidFind | train | function pidFind(pid) {
if (!_.isFinite(pid)) return false;
try {
if (runningAsRoot()) {
return process.kill(pid, 0);
} else {
return !!ps(pid);
}
} catch (e) {
return false;
}
} | javascript | {
"resource": ""
} |
q714 | getGid | train | function getGid(groupname, options) {
const gid = _.tryOnce(findGroup(groupname, options), 'id');
return _.isUndefined(gid) ? null : gid;
} | javascript | {
"resource": ""
} |
q715 | getAttrs | train | function getAttrs(file) {
const sstat = fs.lstatSync(file);
return {
mode: _getUnixPermFromMode(sstat.mode), type: fileType(file),
atime: sstat.atime, ctime: sstat.ctime, mtime: sstat.mtime
};
} | javascript | {
"resource": ""
} |
q716 | addAuthHeaders | train | function addAuthHeaders ({
auth,
bearerToken,
headers,
overrideHeaders=false,
}) {
if (overrideHeaders) return
if (bearerToken) return {
headers: { ...headers, Authorization: `Bearer ${ bearerToken }` }
}
if (auth) {
const username = auth.username || ''
const password = auth.password || ''
const encodedToken = Base64.btoa(`${ username }:${ password }`)
return {
headers: { ...headers, Authorization: `Basic ${ encodedToken }` }
}
}
} | javascript | {
"resource": ""
} |
q717 | getUid | train | function getUid(username, options) {
const uid = _.tryOnce(findUser(username, options), 'id');
return _.isUndefined(uid) ? null : uid;
} | javascript | {
"resource": ""
} |
q718 | includeCSRFToken | train | function includeCSRFToken ({ method, csrf=true, headers }) {
if (!csrf || !CSRF_METHODS.includes(method)) return
const token = getTokenFromDocument(csrf)
if (!token) return
return {
headers: { ...headers, 'X-CSRF-Token': token }
}
} | javascript | {
"resource": ""
} |
q719 | HttpBackend | train | function HttpBackend() {
this.requests = [];
this.expectedRequests = [];
const self = this;
// All the promises our flush requests have returned. When all these promises are
// resolved or rejected, there are no more flushes in progress.
// For simplicity we never remove promises from this loop: this is a mock utility
// for short duration tests, so this keeps it simpler.
this._flushPromises = [];
// the request function dependency that the SDK needs.
this.requestFn = function(opts, callback) {
const req = new Request(opts, callback);
console.log(`${Date.now()} HTTP backend received request: ${req}`);
self.requests.push(req);
const abort = function() {
const idx = self.requests.indexOf(req);
if (idx >= 0) {
console.log("Aborting HTTP request: %s %s", opts.method,
opts.uri);
self.requests.splice(idx, 1);
req.callback("aborted");
}
};
return {
abort: abort,
};
};
// very simplistic mapping from the whatwg fetch interface onto the request
// interface, so we can use the same mock backend for both.
this.fetchFn = function(input, init) {
init = init || {};
const requestOpts = {
uri: input,
method: init.method || 'GET',
body: init.body,
};
return new Promise((resolve, reject) => {
function callback(err, response, body) {
if (err) {
reject(err);
}
resolve({
ok: response.statusCode >= 200 && response.statusCode < 300,
json: () => JSON.parse(body),
});
};
const req = new Request(requestOpts, callback);
console.log(`HTTP backend received request: ${req}`);
self.requests.push(req);
});
};
} | javascript | {
"resource": ""
} |
q720 | train | function(opts) {
opts = opts || {};
if (this.expectedRequests.length === 0) {
// calling flushAllExpected when there are no expectations is a
// silly thing to do, and probably means that your test isn't
// doing what you think it is doing (or it is racy). Hence we
// reject this, rather than resolving immediately.
return Promise.reject(new Error(
`flushAllExpected called with an empty expectation list`,
));
}
const waitTime = opts.timeout === undefined ? 1000 : opts.timeout;
const endTime = waitTime + Date.now();
let flushed = 0;
const iterate = () => {
const timeRemaining = endTime - Date.now();
if (timeRemaining <= 0) {
throw new Error(
`Timed out after flushing ${flushed} requests; `+
`${this.expectedRequests.length} remaining`,
);
}
return this.flush(
undefined, undefined, timeRemaining,
).then((f) => {
flushed += f;
if (this.expectedRequests.length === 0) {
// we're done
return null;
}
return iterate();
});
};
const prom = new Promise((resolve, reject) => {
iterate().then(() => {
resolve(flushed);
}, (e) => {
reject(e);
});
});
this._flushPromises.push(prom);
return prom;
} | javascript | {
"resource": ""
} |
|
q721 | train | function(method, path, data) {
const pendingReq = new ExpectedRequest(method, path, data);
this.expectedRequests.push(pendingReq);
return pendingReq;
} | javascript | {
"resource": ""
} |
|
q722 | ExpectedRequest | train | function ExpectedRequest(method, path, data) {
this.method = method;
this.path = path;
this.data = data;
this.response = null;
this.checks = [];
} | javascript | {
"resource": ""
} |
q723 | train | function(code, data, rawBody) {
this.response = {
response: {
statusCode: code,
headers: {
'content-type': 'application/json',
},
},
body: data || "",
err: null,
rawBody: rawBody || false,
};
} | javascript | {
"resource": ""
} |
|
q724 | train | function(code, err) {
this.response = {
response: {
statusCode: code,
headers: {},
},
body: null,
err: err,
};
} | javascript | {
"resource": ""
} |
|
q725 | Request | train | function Request(opts, callback) {
this.opts = opts;
this.callback = callback;
Object.defineProperty(this, 'method', {
get: function() {
return opts.method;
},
});
Object.defineProperty(this, 'path', {
get: function() {
return opts.uri;
},
});
/**
* Parse the body of the request as a JSON object and return it.
*/
Object.defineProperty(this, 'data', {
get: function() {
return opts.body ? JSON.parse(opts.body) : opts.body;
},
});
/**
* Return the raw body passed to request
*/
Object.defineProperty(this, 'rawData', {
get: function() {
return opts.body;
},
});
Object.defineProperty(this, 'queryParams', {
get: function() {
return opts.qs;
},
});
Object.defineProperty(this, 'headers', {
get: function() {
return opts.headers || {};
},
});
} | javascript | {
"resource": ""
} |
q726 | findUser | train | function findUser(user, options) {
options = _.opts(options, {refresh: true, throwIfNotFound: true});
if (_.isString(user) && user.match(/^[0-9]+$/)) {
user = parseInt(user, 10);
}
return _findUser(user, options);
} | javascript | {
"resource": ""
} |
q727 | forAsync | train | function forAsync(items, iter, callback) {
var keys = Object.keys(items);
var step = function (err, callback) {
nextTick(function () {
if (err) {
return callback(err);
}
if (keys.length === 0) {
return callback();
}
var key = keys.pop();
iter(items[key], key, function (err) {
step(err, callback);
});
});
};
step(null, callback);
} | javascript | {
"resource": ""
} |
q728 | getOptions | train | function getOptions(merge) {
var options = {
root: null,
schemas: {},
add: [],
formats: {},
fresh: false,
multi: false,
timeout: 5000,
checkRecursive: false,
banUnknownProperties: false,
languages: {},
language: null
};
return copyProps(options, merge);
} | javascript | {
"resource": ""
} |
q729 | loadSchemaList | train | function loadSchemaList(job, uris, callback) {
uris = uris.filter(function (value) {
return !!value;
});
if (uris.length === 0) {
nextTick(function () {
callback();
});
return;
}
var sweep = function () {
if (uris.length === 0) {
nextTick(callback);
return;
}
forAsync(uris, function (uri, i, callback) {
if (!uri) {
out.writeln('> ' + style.error('cannot load') + ' "' + tweakURI(uri) + '"');
callback();
}
out.writeln('> ' + style.accent('load') + ' + ' + tweakURI(uri));
loader.load(uri, job.context.options, function (err, schema) {
if (err) {
return callback(err);
}
job.context.tv4.addSchema(uri, schema);
uris = job.context.tv4.getMissingUris();
callback();
});
}, function (err) {
if (err) {
job.error = err;
return callback(null);
}
// sweep again
sweep();
});
};
sweep();
} | javascript | {
"resource": ""
} |
q730 | validateObject | train | function validateObject(job, object, callback) {
if (typeof object.value === 'undefined') {
var onLoad = function (err, obj) {
if (err) {
job.error = err;
return callback(err);
}
object.value = obj;
doValidateObject(job, object, callback);
};
var opts = {
timeout: (job.context.options.timeout || 5000)
};
//TODO verify http:, file: and plain paths all load properly
if (object.path) {
loader.loadPath(object.path, opts, onLoad);
}
else if (object.url) {
loader.load(object.url, opts, onLoad);
}
else {
callback(new Error('object missing value, path or url'));
}
}
else {
doValidateObject(job, object, callback);
}
} | javascript | {
"resource": ""
} |
q731 | addGroup | train | function addGroup(group, options) {
options = _.opts(options, {gid: null});
if (!runningAsRoot()) return;
if (!group) throw new Error('You must provide a group');
if (groupExists(group)) {
return;
}
if (isPlatform('linux')) {
_addGroupLinux(group, options);
} else if (isPlatform('osx')) {
_addGroupOsx(group, options);
} else if (isPlatform('windows')) {
throw new Error(`Don't know how to add group ${group} on Windows`);
} else {
throw new Error(`Don't know how to add group ${group} in current platform`);
}
} | javascript | {
"resource": ""
} |
q732 | assertProperties | train | function assertProperties(object, path, properties) {
let errors = [];
(properties || []).forEach((property) => {
if (get(object, property, undefined) === undefined) {
errors = [...errors, { path, id: object.id, error: `${object.type} is missing the '${property}' property` }];
}
});
return errors;
} | javascript | {
"resource": ""
} |
q733 | assertDeprecations | train | function assertDeprecations(object, path, properties) {
let errors = [];
(properties || []).forEach(({ property, use }) => {
if (get(object, property, undefined) !== undefined) {
errors = [
...errors,
{
path,
id: object.id,
error: `${object.type} is using the '${property}' property. It's deprecated and will be removed.${use ? ` Use '${use}' instead` : ''}.`,
},
];
}
});
return errors;
} | javascript | {
"resource": ""
} |
q734 | validatePage | train | function validatePage(page, path) {
let errors = [];
// Check for required properties
errors = [...errors, ...assertProperties(page, path, requiredProperties[page.type])];
if (page.children) {
// Check that children is an array
if (!Array.isArray(page.children)) {
errors = [...errors, { path, error: 'Children must be an array' }];
return errors;
}
page.children.forEach((node, index) => {
errors = [...errors, ...validateNode(node, [...path, 'children', index], [page])];
});
}
return errors;
} | javascript | {
"resource": ""
} |
q735 | prepend | train | function prepend(file, text, options) {
options = _.sanitize(options, {encoding: 'utf-8'});
const encoding = options.encoding;
if (!exists(file)) {
write(file, text, {encoding: encoding});
} else {
const currentText = read(file, {encoding: encoding});
write(file, text + currentText, {encoding: encoding});
}
} | javascript | {
"resource": ""
} |
q736 | getHtml | train | function getHtml(methods) {
return [
'<!doctype html>',
'<html lang="en">',
'<head>',
'<title>API Index</title>',
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>',
'<link rel="stylesheet" href="//yastatic.net/bootstrap/3.1.1/css/bootstrap.min.css"/>',
'</head>',
'<body class="container">',
'<div class="col-md-7">',
Object.keys(methods).map(function (name) {
return getMethodHtml(methods[name]);
}).join(''),
'</div>',
'</body>',
'</html>'
].join('');
} | javascript | {
"resource": ""
} |
q737 | getMethodHtml | train | function getMethodHtml(method) {
var params = method.getParams();
return [
'<h3>', method.getName(), '</h3>',
method.getOption('executeOnServerOnly') &&
'<span class="label label-primary" style="font-size:0.5em;vertical-align:middle">server only</span>',
'<p>', method.getDescription(), '</p>',
Object.keys(params).length &&
[
'<table class="table table-bordered table-condensed">',
'<thead>',
'<tr>',
'<th class="col-md-2">Name</th>',
'<th class="col-md-2">Type</th>',
'<th>Description</th>',
'</tr>',
'</thead>',
'<tbody>',
Object.keys(params).map(function (key) {
return getMethodParamHtml(key, params[key]);
}).join(''),
'</tbody>',
'</table>'
].join('')
].filter(Boolean).join('');
} | javascript | {
"resource": ""
} |
q738 | getMethodParamHtml | train | function getMethodParamHtml(name, param) {
return [
'<tr>',
'<td>',
name,
param.required ?
'<span title="Required field" style="color:red;cursor:default"> *</span>' : '',
'</td>',
'<td>', param.type || 'As is', '</td>',
'<td>', param.description, '</td>',
'</tr>'
].join('');
} | javascript | {
"resource": ""
} |
q739 | buildMethodName | train | function buildMethodName(req) {
return [
req.params.service,
req.params.subservice
].filter(Boolean).join('-');
} | javascript | {
"resource": ""
} |
q740 | eachLine | train | function eachLine(file, lineProcessFn, finallyFn, options) {
if (arguments.length === 2) {
if (_.isFunction(lineProcessFn)) {
finallyFn = null;
options = {};
} else {
options = lineProcessFn;
lineProcessFn = null;
}
} else if (arguments.length === 3) {
if (_.isFunction(finallyFn)) {
options = {};
} else {
finallyFn = null;
options = finallyFn;
}
}
options = _.sanitize(options, {reverse: false, eachLine: null, finally: null, encoding: 'utf-8'});
finallyFn = finallyFn || options.finally;
lineProcessFn = lineProcessFn || options.eachLine;
const data = read(file, _.pick(options, 'encoding'));
const lines = data.split('\n');
if (options.reverse) lines.reverse();
const newLines = [];
_.each(lines, (line, index) => {
const res = lineProcessFn(line, index);
newLines.push(res);
// Returning false from lineProcessFn will allow us early aborting the loop
return res;
});
if (options.reverse) newLines.reverse();
if (finallyFn !== null) finallyFn(newLines.join('\n'));
} | javascript | {
"resource": ""
} |
q741 | write | train | function write(file, text, options) {
options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true});
file = normalize(file);
try {
fs.writeFileSync(file, text, options);
} catch (e) {
if (e.code === 'ENOENT' && options.retryOnENOENT) {
// If trying to create the parent failed, there is no point on retrying
try {
mkdir(path.dirname(file));
} catch (emkdir) {
throw e;
}
write(file, text, _.opts(options, {retryOnENOENT: false}, {mode: 'overwite'}));
} else {
throw e;
}
}
} | javascript | {
"resource": ""
} |
q742 | walkDir | train | function walkDir(file, callback, options) {
file = path.resolve(file);
if (!_.isFunction(callback)) throw new Error('You must provide a callback function');
options = _.opts(options, {followSymLinks: false, maxDepth: Infinity});
const prefix = options.prefix || file;
function _walkDir(f, depth) {
const type = fileType(f);
const relativePath = stripPathPrefix(f, prefix);
const metaData = {type: type, file: relativePath};
if (file === f) metaData.topDir = true;
const result = callback(f, metaData);
if (result === false) return false;
if (type === 'directory' || (type === 'link' && options.followSymLinks && isDirectory(f, options.followSymLinks))) {
let shouldContinue = true;
if (depth >= options.maxDepth) {
return;
}
_.each(fs.readdirSync(f), (elem) => {
shouldContinue = _walkDir(path.join(f, elem), depth + 1);
return shouldContinue;
});
}
}
_walkDir(file, 0);
} | javascript | {
"resource": ""
} |
q743 | yamlFileGet | train | function yamlFileGet(file, keyPath, options) {
if (_.isPlainObject(keyPath) && arguments.length === 2) {
options = keyPath;
keyPath = undefined;
}
options = _.sanitize(options, {encoding: 'utf-8', default: ''});
const content = yaml.safeLoad(read(file, _.pick(options, 'encoding')));
const value = _extractValue(content, keyPath);
return _.isUndefined(value) ? options.default : value;
} | javascript | {
"resource": ""
} |
q744 | setAttrs | train | function setAttrs(file, attrs) {
if (isLink(file)) return;
if (_.every([attrs.atime, attrs.mtime], _.identity)) {
fs.utimesSync(file, new Date(attrs.atime), new Date(attrs.mtime));
}
if (attrs.mode) {
chmod(file, attrs.mode);
}
} | javascript | {
"resource": ""
} |
q745 | groupExists | train | function groupExists(group) {
if (isPlatform('windows')) {
throw new Error('Don\'t know how to check for group existence on Windows');
} else {
if (_.isEmpty(findGroup(group, {refresh: true, throwIfNotFound: false}))) {
return false;
} else {
return true;
}
}
} | javascript | {
"resource": ""
} |
q746 | readable | train | function readable(file) {
if (!exists(file)) {
return false;
} else {
try {
fs.accessSync(file, fs.R_OK);
} catch (e) {
return false;
}
return true;
}
} | javascript | {
"resource": ""
} |
q747 | readableBy | train | function readableBy(file, user) {
if (!exists(file)) {
return readableBy(path.dirname(file), user);
}
const userData = findUser(user);
if (userData.id === 0) {
return true;
} else if (userData.id === process.getuid()) {
return readable(file);
} else {
return _accesibleByUser(userData, file, fs.R_OK);
}
} | javascript | {
"resource": ""
} |
q748 | writable | train | function writable(file) {
if (!exists(file)) {
return writable(path.dirname(file));
} else {
try {
fs.accessSync(file, fs.W_OK);
} catch (e) {
return false;
}
return true;
}
} | javascript | {
"resource": ""
} |
q749 | writableBy | train | function writableBy(file, user) {
function _writableBy(f, userData) {
if (!exists(f)) {
return _writableBy(path.dirname(f), userData);
} else {
return _accesibleByUser(userData, f, fs.W_OK);
}
}
const uData = findUser(user);
// root can always write
if (uData.id === 0) {
return true;
} else if (uData.id === process.getuid()) {
return writable(file);
} else {
return _writableBy(file, uData);
}
} | javascript | {
"resource": ""
} |
q750 | executable | train | function executable(file) {
try {
fs.accessSync(file, fs.X_OK);
return true;
} catch (e) {
return false;
}
} | javascript | {
"resource": ""
} |
q751 | executableBy | train | function executableBy(file, user) {
if (!exists(file)) {
return false;
}
const userData = findUser(user);
if (userData.id === 0) {
// Root can do anything but execute a file with no exec permissions
const mode = fs.lstatSync(file).mode;
return !!(mode & parseInt('00111', 8));
} else if (userData.id === process.getuid()) {
return executable(file);
} else {
return _accesibleByUser(userData, file, fs.X_OK);
}
} | javascript | {
"resource": ""
} |
q752 | split | train | function split(p) {
const components = p.replace(/\/+/g, '/').replace(/\/+$/, '').split(path.sep);
if (path.isAbsolute(p) && components[0] === '') {
components[0] = '/';
}
return components;
} | javascript | {
"resource": ""
} |
q753 | join | train | function join() {
const components = _.isArray(arguments[0]) ? arguments[0] : _.toArray(arguments);
return path.join.apply(null, components).replace(/(.+)\/+$/, '$1');
} | javascript | {
"resource": ""
} |
q754 | backup | train | function backup(source, options) {
options = _.sanitize(options, {destination: null});
let dest = options.destination;
if (dest === null) {
dest = `${source.replace(/\/*$/, '')}_${Date.now()}`;
}
copy(source, dest);
return dest;
} | javascript | {
"resource": ""
} |
q755 | fromEuler | train | function fromEuler (q, euler) {
var x = euler[0]
var y = euler[1]
var z = euler[2]
var cx = Math.cos(x / 2)
var cy = Math.cos(y / 2)
var cz = Math.cos(z / 2)
var sx = Math.sin(x / 2)
var sy = Math.sin(y / 2)
var sz = Math.sin(z / 2)
q[0] = sx * cy * cz + cx * sy * sz
q[1] = cx * sy * cz - sx * cy * sz
q[2] = cx * cy * sz + sx * sy * cz
q[3] = cx * cy * cz - sx * sy * sz
return q
} | javascript | {
"resource": ""
} |
q756 | yamlFileSet | train | function yamlFileSet(file, keyPath, value, options) {
if (_.isPlainObject(keyPath)) { // key is keyMapping
if (!_.isUndefined(options)) {
throw new Error('Wrong parameters. Cannot specify a keymapping and a value at the same time.');
}
if (_.isPlainObject(value)) {
options = value;
value = null;
} else {
options = {};
}
} else if (!_.isString(keyPath) && !_.isArray(keyPath)) {
throw new Error('Wrong parameter `keyPath`.');
}
options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true});
if (!exists(file)) {
touch(file);
}
let content = yaml.safeLoad(read(file, _.pick(options, 'encoding')));
if (_.isUndefined(content)) {
content = {};
}
content = _setValue(content, keyPath, value);
write(file, yaml.safeDump(content), options);
} | javascript | {
"resource": ""
} |
q757 | isFile | train | function isFile(file, options) {
options = _.sanitize(options, {acceptLinks: true});
try {
return _fileStats(file, options).isFile();
} catch (e) {
return false;
}
} | javascript | {
"resource": ""
} |
q758 | findGroup | train | function findGroup(group, options) {
options = _.opts(options, {refresh: true, throwIfNotFound: true});
if (_.isString(group) && group.match(/^[0-9]+$/)) {
group = parseInt(group, 10);
}
return _findGroup(group, options);
} | javascript | {
"resource": ""
} |
q759 | addUser | train | function addUser(user, options) {
if (!runningAsRoot()) return;
if (!user) throw new Error('You must provide an username');
options = _.opts(options, {systemUser: false, home: null, password: null, gid: null, uid: null, groups: []});
if (userExists(user)) {
return;
}
if (isPlatform('linux')) {
_addUserLinux(user, options);
} else if (isPlatform('osx')) {
_addUserOsx(user, options);
} else if (isPlatform('windows')) {
throw new Error("Don't know how to add user in Windows");
} else {
throw new Error("Don't know how to add user in current platform");
}
} | javascript | {
"resource": ""
} |
q760 | fromQuat | train | function fromQuat (v, q) {
var sqx = q[0] * q[0]
var sqy = q[1] * q[1]
var sqz = q[2] * q[2]
var sqw = q[3] * q[3]
v[0] = Math.atan2(2 * (q[0] * q[3] - q[1] * q[2]), (sqw - sqx - sqy + sqz))
v[1] = Math.asin(clamp(2 * (q[0] * q[2] + q[1] * q[3]), -1, 1))
v[2] = Math.atan2(2 * (q[2] * q[3] - q[0] * q[1]), (sqw + sqx - sqy - sqz))
return v
} | javascript | {
"resource": ""
} |
q761 | sendAjaxRequest | train | function sendAjaxRequest(url, data, execOptions) {
var xhr = new XMLHttpRequest();
var d = vow.defer();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
d.resolve(JSON.parse(xhr.responseText));
} else {
d.reject(xhr);
}
}
};
xhr.ontimeout = function () {
d.reject(new ApiError(ApiError.TIMEOUT, 'Timeout was reached while waiting for ' + url));
xhr.abort();
};
// shim for browsers which don't support timeout/ontimeout
if (typeof xhr.timeout !== 'number' && execOptions.timeout) {
var timeoutId = setTimeout(xhr.ontimeout.bind(xhr), execOptions.timeout);
var oldHandler = xhr.onreadystatechange;
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
clearTimeout(timeoutId);
}
oldHandler();
};
}
xhr.open('POST', url, true);
xhr.timeout = execOptions.timeout;
xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(data);
return d.promise();
} | javascript | {
"resource": ""
} |
q762 | Api | train | function Api(basePath, options) {
this._basePath = basePath;
options = options || {};
this._options = {
enableBatching: options.hasOwnProperty('enableBatching') ?
options.enableBatching :
true,
timeout: options.timeout || 0
};
this._batch = [];
this._deferreds = {};
} | javascript | {
"resource": ""
} |
q763 | train | function (methodName, params, execOptions) {
execOptions = execOptions || {};
var options = {
enableBatching: execOptions.hasOwnProperty('enableBatching') ?
execOptions.enableBatching :
this._options.enableBatching,
timeout: execOptions.timeout || this._options.timeout
};
return options.enableBatching ?
this._execWithBatching(methodName, params, options) :
this._execWithoutBatching(methodName, params, options);
} | javascript | {
"resource": ""
} |
|
q764 | train | function (methodName, params, execOptions) {
var defer = vow.defer();
var url = this._basePath + methodName;
var data = JSON.stringify(params);
sendAjaxRequest(url, data, execOptions).then(
this._resolvePromise.bind(this, defer),
this._rejectPromise.bind(this, defer)
);
return defer.promise();
} | javascript | {
"resource": ""
} |
|
q765 | train | function (methodName, params, execOptions) {
var requestId = this._getRequestId(methodName, params);
var promise = this._getRequestPromise(requestId);
if (!promise) {
this._addToBatch(methodName, params);
promise = this._createPromise(requestId);
this._run(execOptions);
}
return promise;
} | javascript | {
"resource": ""
} |
|
q766 | train | function (execOptions) {
var url = this._basePath + 'batch';
var data = JSON.stringify({methods: this._batch});
sendAjaxRequest(url, data, execOptions).then(
this._resolvePromises.bind(this, this._batch),
this._rejectPromises.bind(this, this._batch)
);
this._batch = [];
} | javascript | {
"resource": ""
} |
|
q767 | train | function (defer, response) {
var error = response.error;
if (error) {
defer.reject(new ApiError(error.type, error.message, error.data));
} else {
defer.resolve(response.data);
}
} | javascript | {
"resource": ""
} |
|
q768 | train | function (batch, response) {
var data = response.data;
for (var i = 0, requestId; i < batch.length; i++) {
requestId = this._getRequestId(batch[i].method, batch[i].params);
this._resolvePromise(this._deferreds[requestId], data[i]);
delete this._deferreds[requestId];
}
} | javascript | {
"resource": ""
} |
|
q769 | train | function (defer, xhr) {
var errorType = xhr.type || xhr.status;
var errorMessage = xhr.responseText || xhr.message || xhr.statusText;
defer.reject(new ApiError(errorType, errorMessage));
} | javascript | {
"resource": ""
} |
|
q770 | train | function (batch, xhr) {
for (var i = 0, requestId; i < batch.length; i++) {
requestId = this._getRequestId(batch[i].method, batch[i].params);
this._rejectPromise(this._deferreds[requestId], xhr);
delete this._deferreds[requestId];
}
} | javascript | {
"resource": ""
} |
|
q771 | append | train | function append(file, text, options) {
options = _.sanitize(options, {atNewLine: false, encoding: 'utf-8'});
if (!exists(file)) {
write(file, text, {encoding: options.encoding});
} else {
if (options.atNewLine && !text.match(/^\n/) && exists(file)) text = `\n${text}`;
fs.appendFileSync(file, text, {encoding: options.encoding});
}
} | javascript | {
"resource": ""
} |
q772 | vowExec | train | function vowExec(cmd) {
var defer = vow.defer();
exec(cmd, function (err, stdout, stderr) {
if (err) {
defer.reject({err: err, stderr: stderr});
} else {
defer.resolve(stdout.trim());
}
});
return defer.promise();
} | javascript | {
"resource": ""
} |
q773 | compareVersions | train | function compareVersions(fstVer, sndVer) {
if (semver.lt(fstVer, sndVer)) {
return 1;
}
if (semver.gt(fstVer, sndVer)) {
return -1;
}
return 0;
} | javascript | {
"resource": ""
} |
q774 | commitAllChanges | train | function commitAllChanges(msg) {
return vowExec(util.format('git commit -a -m "%s" -n', msg))
.fail(function (res) {
return vow.reject('Commit failed:\n' + res.stderr);
});
} | javascript | {
"resource": ""
} |
q775 | changelog | train | function changelog(from, to) {
return vowExec(util.format('git log --format="%%s" %s..%s', from, to))
.then(function (stdout) {
return stdout.split('\n');
});
} | javascript | {
"resource": ""
} |
q776 | mdLogEntry | train | function mdLogEntry(version, log) {
return util.format(
'### %s\n%s\n\n',
version,
log.map(function (logItem) {
return ' * ' + logItem;
}).join('\n')
);
} | javascript | {
"resource": ""
} |
q777 | iniFileSet | train | function iniFileSet(file, section, key, value, options) {
options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true});
if (typeof key === 'object') {
if (typeof value === 'object') {
options = value;
} else {
options = {};
}
}
if (!exists(file)) {
touch(file, '', options);
} else if (!isFile(file)) {
throw new Error(`File ${file} is not a file`);
}
const config = ini.parse(read(file, {encoding: options.encoding}));
if (!_.isEmpty(section)) {
config[section] = config[section] || {};
section = config[section];
} else {
section = config;
}
if (typeof key === 'string') {
section[key] = value;
} else {
_.merge(section, key);
}
write(file, ini.stringify(config), options);
} | javascript | {
"resource": ""
} |
q778 | puts | train | function puts(file, text, options) {
options = _.sanitize(options, {atNewLine: false, encoding: 'utf-8'});
append(file, `${text}\n`, options);
} | javascript | {
"resource": ""
} |
q779 | getPhotoUrl | train | function getPhotoUrl(data) {
return FLICK_PHOTO_URL_TEMPLATE
.replace('{farm-id}', data.farm)
.replace('{server-id}', data.server)
.replace('{id}', data.id)
.replace('{secret}', data.secret)
.replace('{size}', 'm');
} | javascript | {
"resource": ""
} |
q780 | link | train | function link(target, location, options) {
options = _.sanitize(options, {force: false});
if (options.force && isLink(location)) {
fileDelete(location);
}
if (!path.isAbsolute(target)) {
const cwd = process.cwd();
process.chdir(path.dirname(location));
try {
fs.symlinkSync(target, path.basename(location));
} finally {
try { process.chdir(cwd); } catch (e) { /* not empty */ }
}
} else {
fs.symlinkSync(target, location);
}
} | javascript | {
"resource": ""
} |
q781 | setDefaults | train | function setDefaults ({ headers={}, overrideHeaders=false, ...rest }) {
return {
...DEFAULTS,
headers: overrideHeaders ? headers : { ...DEFAULT_HEADERS, ...headers },
...rest,
}
} | javascript | {
"resource": ""
} |
q782 | deleteUser | train | function deleteUser(user) {
if (!runningAsRoot()) return;
if (!user) throw new Error('You must provide an username');
if (!userExists(user)) {
return;
}
const userdelBin = _safeLocateBinary('userdel');
const deluserBin = _safeLocateBinary('deluser');
if (isPlatform('linux')) {
if (userdelBin !== null) { // most modern systems
runProgram(userdelBin, [user]);
} else {
if (_isBusyboxBinary(deluserBin)) { // busybox-based systems
runProgram(deluserBin, [user]);
} else {
throw new Error(`Don't know how to delete user ${user} on this strange linux`);
}
}
} else if (isPlatform('osx')) {
runProgram('dscl', ['.', '-delete', `/Users/${user}`]);
} else if (isPlatform('windows')) {
throw new Error('Don\'t know how to delete user in Windows');
} else {
throw new Error('Don\'t know how to delete user in current platform');
}
} | javascript | {
"resource": ""
} |
q783 | lookForBinary | train | function lookForBinary(binary, pathList) {
let envPath = _.toArrayIfNeeded(pathList);
if (_.isEmpty(envPath)) {
envPath = (process.env.PATH || '').split(path.delimiter);
}
const foundPath = _.first(_.filter(envPath, (dir) => {
return fileExists(path.join(dir, binary));
}));
return foundPath ? path.join(foundPath, binary) : null;
} | javascript | {
"resource": ""
} |
q784 | parse | train | function parse(str, opts) {
var parser = new Parser(str, opts);
return {attrs: parser._readProtocol(), imports: parser._imports};
} | javascript | {
"resource": ""
} |
q785 | Tokenizer | train | function Tokenizer(str) {
this._str = str;
this._pos = 0;
this._queue = new BoundedQueue(3); // Bounded queue of last emitted tokens.
this._token = undefined; // Current token.
this._doc = undefined; // Javadoc.
} | javascript | {
"resource": ""
} |
q786 | Parser | train | function Parser(str, opts) {
this._oneWayVoid = !!(opts && opts.oneWayVoid);
this._reassignJavadoc = !!(opts && opts.reassignJavadoc);
this._imports = [];
this._tk = new Tokenizer(str);
this._tk.next(); // Prime tokenizer.
} | javascript | {
"resource": ""
} |
q787 | reassignJavadoc | train | function reassignJavadoc(from, to) {
if (!(from.doc instanceof Javadoc)) {
// Nothing to transfer.
return from;
}
to.doc = from.doc;
delete from.doc;
return Object.keys(from).length === 1 ? from.type : from;
} | javascript | {
"resource": ""
} |
q788 | xmlFileGet | train | function xmlFileGet(file, element, attributeName, options) {
options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true, default: null});
const doc = loadXmlFile(file, options);
const node = getXmlNode(doc, element);
let value;
if (_.isEmpty(attributeName)) {
value = _.map(node.childNodes, 'nodeValue');
} else {
value = node.getAttribute(attributeName);
// Always return an array
value = [value];
}
return _.isUndefined(value) ? options.default : value;
} | javascript | {
"resource": ""
} |
q789 | exists | train | function exists(file) {
try {
fs.lstatSync(file);
return true;
} catch (e) {
if (e.code === 'ENOENT' || e.code === 'ENOTDIR') {
return false;
} else {
throw e;
}
}
} | javascript | {
"resource": ""
} |
q790 | getOverloadedConfigFromEnvironment | train | function getOverloadedConfigFromEnvironment() {
var env = typeof document === 'undefined' ? {} : document.documentElement.dataset;
var platformUrl = env.zpPlatformUrl;
var appName = env.zpSandboxid;
return {
platformUrl: platformUrl,
appName: appName
};
} | javascript | {
"resource": ""
} |
q791 | _gpfDefAttr | train | function _gpfDefAttr (name, base, definition) {
var
isAlias = name.charAt(0) === "$",
fullName,
result;
if (isAlias) {
name = name.substr(1);
fullName = name + "Attribute";
} else {
fullName = name;
}
result = _gpfDefAttrBase(fullName, base, definition);
if (isAlias) {
_gpfAlias(result, name);
}
return result;
} | javascript | {
"resource": ""
} |
q792 | train | function (expectedClass) {
_gpfAssertAttributeClassOnly(expectedClass);
var result = new _gpfA.Array();
result._array = this._array.filter(function (attribute) {
return attribute instanceof expectedClass;
});
return result;
} | javascript | {
"resource": ""
} |
|
q793 | train | function (to, callback, param) {
_gpfObjectForEach(this._members, function (attributeArray, member) {
member = _gpfDecodeAttributeMember(member);
attributeArray._array.forEach(function (attribute) {
if (!callback || callback(member, attribute, param)) {
to.add(member, attribute);
}
});
});
return to;
} | javascript | {
"resource": ""
} |
|
q794 | train | function (classDef) {
var attributes,
Super;
while (classDef) { // !undefined && !null
attributes = classDef._attributes;
if (attributes) {
attributes._copy(this);
}
Super = classDef._Super;
if (Super === Object) { // Can't go upper
break;
} else {
classDef = _gpfGetClassDefinition(Super);
}
}
return this;
} | javascript | {
"resource": ""
} |
|
q795 | train | function (member, attribute) {
_gpfAssertAttributeOnly(attribute);
member = _gpfEncodeAttributeMember(member);
var array = this._members[member];
if (undefined === array) {
array = this._members[member] = new _gpfA.Array();
}
array._array.push(attribute);
++this._count;
} | javascript | {
"resource": ""
} |
|
q796 | train | function (member) {
member = _gpfEncodeAttributeMember(member);
var result = this._members[member];
if (undefined === result || !(result instanceof _gpfA.Array)) {
return _gpfEmptyMemberArray;
}
return result;
} | javascript | {
"resource": ""
} |
|
q797 | train | function () {
var result = [];
_gpfObjectForEach(this._members, function (attributes, member) {
_gpfIgnore(attributes);
result.push(_gpfDecodeAttributeMember(member));
});
return result;
} | javascript | {
"resource": ""
} |
|
q798 | loadFileAsString | train | function loadFileAsString(path, replaceWhiteSpaces){
var file = new java.io.File(path);
var fr = new java.io.FileReader(file);
var br = new java.io.BufferedReader(fr);
var line;
var lines = "";
while((line = br.readLine()) != null){
if(replaceWhiteSpaces){
lines = lines + line.replace(" ", "");
}else{
lines = lines + line;
}
}
return lines;
} | javascript | {
"resource": ""
} |
q799 | getFilesList | train | function getFilesList(path, includes, excludes){
// Init default vars values
includes = (includes === undefined || includes == null || includes == '') ? "**" : includes;
excludes = (excludes === undefined || excludes == null || excludes == '') ? "" : excludes;
var fs = project.createDataType("fileset");
fs.setDir(new java.io.File(path));
if(includes != ""){
fs.setIncludes(includes);
}
if(excludes != ""){
fs.setExcludes(excludes);
}
var srcFiles = fs.getDirectoryScanner(project).getIncludedFiles();
var result = [];
for (var i = 0; i<srcFiles.length; i++){
result.push(srcFiles[i]);
}
return result;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.