_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q8100
|
parseBody
|
train
|
function parseBody (body, content_type) {
if (typeof(body) === "object" || Array.isArray(body) || !body) {
// no need to parse if it's already an object
return body;
}
let parsed_content_type = content_type_module.parse(content_type);
if (parsed_content_type.type === 'application/json') {
// parse json
return JSON.parse(body);
} else if (parsed_content_type.type === 'application/x-www-form-urlencoded') {
// parse form encoded
return qs_module.parse(body);
} else {
// maybe it's supposed to be literal
return body;
}
}
|
javascript
|
{
"resource": ""
}
|
q8101
|
fixExclude
|
train
|
function fixExclude(exclude_list) {
if (!exclude_list) {
exclude_list = [];
}
exclude_list.push(__filename);
exclude_list.push(__dirname + '/../../tests');
exclude_list.push(__dirname + '/../integrations/koa.js');
exclude_list.push(__dirname + '/../integrations/express.js');
exclude_list.push(__dirname + '/../middleware/cors.js');
return exclude_list;
}
|
javascript
|
{
"resource": ""
}
|
q8102
|
fixOptions
|
train
|
function fixOptions (options) {
if (!options) {
options = {};
}
options.use_sourcemaps = options.use_sourcemaps ? true : false;
options.babelify = fixBabelify(options.babelify);
// options.external = fixExternal(options.external);
options.ignore = fixIgnore(options.ignore);
options.exclude = fixExclude(options.exclude);
return options;
}
|
javascript
|
{
"resource": ""
}
|
q8103
|
docletModel
|
train
|
function docletModel(doclet) {
return function(context, cb) {
logger.debug('doclet', doclet);
var viewModel = _.extend({},
util.rstMixin,
util.docletChildren(context, doclet, util.mainDocletKinds),
// (doclet.kind === 'module' ? {} :
// util.docletChildren(context, doclet, util.subDocletKinds)
// ), {
util.docletChildren(context, doclet, util.subDocletKinds), {
doclet: doclet,
example: util.example
}
);
util.view('doclet.rst', viewModel, cb);
};
}
|
javascript
|
{
"resource": ""
}
|
q8104
|
escapeString
|
train
|
function escapeString(str) {
if(str === undefined) {
throw new Error('\'str\' is required');
}
if(str === null) {
throw new Error('\'str\' must not be null');
}
if(typeof str !== 'string') {
throw new Error('\'str\' must be a string');
}
/*
* Need to escape backslashes (\) first because escaping ' and " will also
* add a \, which interferes with \ escaping.
*/
var escaped_str = str;
// regex replace all \ to \\
escaped_str = escaped_str.replace(/\\/g, '\\\\');
// regex replace all ' to \'
escaped_str = escaped_str.replace(/'/g, '\\\'');
// regex replace all " to \"
escaped_str = escaped_str.replace(/"/g, '\\"');
return escaped_str;
}
|
javascript
|
{
"resource": ""
}
|
q8105
|
highlight
|
train
|
function highlight (code, lang) {
if (!lang) {
return code
}
var isDiff = DIFF_REGEXP.test(lang)
// Remove the diff suffix. E.g. "javascript.diff".
lang = lang.replace(DIFF_REGEXP, '')
// Ignore unknown languages.
if (!isDiff && !supported(lang)) {
return code
}
return isDiff ? diff(code, lang) : hljs.highlight(lang, code).value
}
|
javascript
|
{
"resource": ""
}
|
q8106
|
diff
|
train
|
function diff (code, lang) {
var sections = []
code.split(/\r?\n/g).forEach(function (line) {
var type
if (CHUNK_REGEXP.test(line)) {
type = 'chunk'
} else if (HEADER_REGEXP.test(line)) {
type = 'header'
} else {
type = PATCH_TYPES[line[0]] || 'null'
line = line.replace(/^[+\-! ]/, '')
}
// Merge data with the previous section where possible.
var previous = sections[sections.length - 1]
if (!previous || previous.type !== type) {
sections.push({
type: type,
lines: [line]
})
return
}
previous.lines.push(line)
})
return highlightSections(sections, lang)
.map(function (section) {
var type = section.type
var value = section.lines.join(SEPARATOR)
return '<span class="diff-' + type + '">' + value + '</span>'
})
.join(SEPARATOR)
}
|
javascript
|
{
"resource": ""
}
|
q8107
|
highlightSections
|
train
|
function highlightSections (sections, lang) {
if (!supported(lang)) {
return sections
}
// Keep track of the most recent stacks.
var additionStack
var deletionStack
sections
.forEach(function (section) {
var type = section.type
// Reset the stacks for metadata types.
if (type === 'header' || type === 'chunk') {
additionStack = deletionStack = null
return
}
var value = section.lines.join(SEPARATOR)
var stack = type === 'deletion' ? deletionStack : additionStack
var highlight = hljs.highlight(lang, value, false, stack)
// Set the top of each stack, depending on context.
if (type === 'addition') {
additionStack = highlight.top
} else if (type === 'deletion') {
deletionStack = highlight.top
} else {
additionStack = deletionStack = highlight.top
}
section.lines = highlight.value.split(SEPARATOR)
})
return sections
}
|
javascript
|
{
"resource": ""
}
|
q8108
|
encode
|
train
|
function encode (filename) {
var ext = path.extname(filename)
var data = fs.readFileSync(filename)
var prefix = 'data:audio/' + ext.substring(1) + ';base64,'
var encoded = new Buffer(data).toString('base64')
return prefix + encoded
}
|
javascript
|
{
"resource": ""
}
|
q8109
|
audioExt
|
train
|
function audioExt (name) {
var ext = path.extname(name)
return ['.wav', '.ogg', '.mp3'].indexOf(ext) > -1 ? ext : null
}
|
javascript
|
{
"resource": ""
}
|
q8110
|
build
|
train
|
function build (instFile) {
var dir = path.dirname(instFile)
var inst = JSON.parse(fs.readFileSync(instFile))
inst.samples = samples(path.join(dir, 'samples'), true)
return JSON.stringify(inst, null, 2)
}
|
javascript
|
{
"resource": ""
}
|
q8111
|
samples
|
train
|
function samples (samplesPath, obj) {
var files = fs.readdirSync(samplesPath).reduce(function (d, name) {
var ext = audioExt(name)
if (ext) d[name.substring(0, name.length - ext.length)] = name
return d
}, {})
var names = Object.keys(files)
var prefix = sharedStart(names)
var len = prefix.length
var samples = names.reduce(function (s, name) {
s[name.substring(len)] = encode(path.join(samplesPath, files[name]))
return s
}, {})
return obj ? samples : JSON.stringify(samples, null, 2)
}
|
javascript
|
{
"resource": ""
}
|
q8112
|
train
|
function(activateNextConnection) {
if ( (count % 20) == 0 || timeoutOccurred) {
timeoutOccurred = false;
exec('killall -9 soffice.bin libreoffice soffice', function(error, stdout, stderr) {
waitForOOState('closed', function() {
exec('libreoffice -headless -nofirststartwizard -accept="socket,host=0.0.0.0,port=8100;urp;StarOffice.Service"');
waitForOOState('open', function() {
activateNextConnection();
});
});
});
} else {
activateNextConnection();
}
count += 1;
}
|
javascript
|
{
"resource": ""
}
|
|
q8113
|
arraySibling
|
train
|
function arraySibling(arr, item, offset) {
var index = arr.indexOf(item);
if (index === -1) {
throw 'item is not in array';
}
if (isArray(offset)) {
return offset.map(function (v) {
return arr[index + v];
});
}
return arr[index + offset];
}
|
javascript
|
{
"resource": ""
}
|
q8114
|
forAll
|
train
|
function forAll(val, handler, reverse) {
if (!reverse) {
if (isArray(val) || isString(val)) {
for (var i = 0; i < val.length; i++) {
if (handler(val[i], i) === false) {
break;
}
}
} else if (isObject(val)) {
for (var _i2 = 0, _Object$keys = Object.keys(val); _i2 < _Object$keys.length; _i2++) {
var key = _Object$keys[_i2];
if (handler(val[key], key) === false) {
break;
}
}
} else if (Number.isInteger(val)) {
for (var _i3 = 0; _i3 < val; _i3++) {
if (handler(_i3, _i3) === false) {
break;
}
}
}
} else {
if (isArray(val) || isString(val)) {
for (var _i4 = val.length - 1; _i4 >= 0; _i4--) {
if (handler(val[_i4], _i4) === false) {
break;
}
}
} else if (isObject(val)) {
var keys = Object.keys(val);
keys.reverse();
for (var _i5 = 0, _keys = keys; _i5 < _keys.length; _i5++) {
var _key = _keys[_i5];
if (handler(val[_key], _key) === false) {
break;
}
}
} else if (Number.isInteger(val)) {
for (var _i6 = val - 1; _i6 >= 0; _i6--) {
if (handler(_i6, _i6) === false) {
break;
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8115
|
executeWithCount
|
train
|
function executeWithCount(func) {
var count = 0;
return function () {
for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
args[_key2] = arguments[_key2];
}
return func.call.apply(func, [this, count++].concat(args));
};
}
|
javascript
|
{
"resource": ""
}
|
q8116
|
executePromiseGetters
|
train
|
function executePromiseGetters(getters) {
var concurrent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var stopped;
var promise = new Promise(function (resolve, reject) {
var r = [];
var chunks = splitArray(getters, concurrent);
var promise = Promise.resolve();
chunks.forEach(function (chunk) {
promise = promise.then(function (result) {
if (result) {
r.push.apply(r, _toConsumableArray(result));
}
if (stopped) {
reject('stopped');
} else {
return Promise.all(chunk.map(function (v) {
return v();
}));
}
});
});
promise.then(function (result) {
r.push.apply(r, _toConsumableArray(result));
resolve(r);
});
});
return {
promise: promise,
destroy: function destroy() {
stopped = true;
}
};
}
|
javascript
|
{
"resource": ""
}
|
q8117
|
getOffsetParent
|
train
|
function getOffsetParent(el) {
var offsetParent = el.offsetParent;
if (!offsetParent || offsetParent === document.body && getComputedStyle(document.body).position === 'static') {
offsetParent = document.body.parentElement;
}
return offsetParent;
}
|
javascript
|
{
"resource": ""
}
|
q8118
|
URLHelper
|
train
|
function URLHelper(baseUrl) {
var _this3 = this;
_classCallCheck(this, URLHelper);
_defineProperty(this, "baseUrl", '');
_defineProperty(this, "search", {});
var t = decodeURI(baseUrl).split('?');
this.baseUrl = t[0];
if (t[1]) {
t[1].split('&').forEach(function (v) {
var t2 = v.split('=');
_this3.search[t2[0]] = t2[1] == null ? '' : decodeURIComponent(t2[1]);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q8119
|
makeStorageHelper
|
train
|
function makeStorageHelper(storage) {
return {
storage: storage,
set: function set(name, value, minutes) {
if (value == null) {
this.storage.removeItem(name);
} else {
this.storage.setItem(name, JSON.stringify({
value: value,
expired_at: minutes ? new Date().getTime() + minutes * 60 * 1000 : null
}));
}
},
get: function get$$1(name) {
var t = this.storage.getItem(name);
if (t) {
t = JSON.parse(t);
if (!t.expired_at || t.expired_at > new Date().getTime()) {
return t.value;
} else {
this.storage.removeItem(name);
}
}
return null;
},
clear: function clear() {
this.storage.clear();
}
};
}
|
javascript
|
{
"resource": ""
}
|
q8120
|
command
|
train
|
function command(os) {
var z = 'ffmpeg';
var os = os||[];
for(var o of os) {
var o = o||{};
for(var k in o) {
if(o[k]==null) continue;
if(k==='stdio') continue;
if(k==='o' || k==='outfile') z += ` "${o[k]}"`;
else if(typeof o[k]==='boolean') z += o[k]? ` -${k}`:'';
else z += ` -${k} ${JSON.stringify(o[k])}`;
}
}
return z;
}
|
javascript
|
{
"resource": ""
}
|
q8121
|
sync
|
train
|
function sync(os) {
var stdio = os.stdio===undefined? STDIO:os.stdio;
return cp.execSync(command(os), {stdio});
}
|
javascript
|
{
"resource": ""
}
|
q8122
|
ffmpeg
|
train
|
function ffmpeg(os) {
var stdio = os.stdio===undefined? STDIO:os.stdio;
return new Promise((fres, frej) => cp.exec(command(os), {stdio}, (err, stdout, stderr) => {
if(err) frej(err);
else fres({stdout, stderr});
}));
}
|
javascript
|
{
"resource": ""
}
|
q8123
|
tokenize
|
train
|
function tokenize (str) {
let pos = 0
let row = 1
let col = 1
let newline = true
let state = CONTENT
let start = 0
let consumingSameLineContent = false
let escapedInlineCounter = 0
let escapedParamCounter = 0
let consumingEscapedParams = false
let consumingUnparsed = false // true when in an @@ block
let lastInlineContentEndPos = void (0)
let unparsedIndentStart = void (0)
const indent = [0]
const tokens = []
function emit (type, value) {
if (arguments.length > 1) {
tokens.push({type: type, value: value})
} else {
tokens.push({type: type})
}
}
function consume (type, next) {
emit(type, str.substring(start, pos))
state = next
start = pos + 1
}
function consumeIfNonEmpty (type, next, escaped) {
let v = str.substring(start, pos)
if (v.length > 0) {
if (escaped) {
const l = escaped.length
for (let i = 0; i < l; i++) {
const es = escaped[i]
v = v.replace(es, es[1])
}
}
emit(type, v)
}
state = next
start = pos + 1
}
function shuffleIfNext (character) {
if (str[pos + 1] === character) {
pos++
start++
return true
} else {
return false
}
}
function err (msg) {
let start = str.lastIndexOf('\n', pos - 1)
start = str.lastIndexOf('\n', start - 1)
start = str.lastIndexOf('\n', start - 1)
const nextNewline = str.indexOf('\n', pos)
const errorLineEnd = nextNewline === -1 ? pos : nextNewline
let end = str.indexOf('\n', errorLineEnd + 1)
if (end === -1) {
end = str.length - 1
} else {
end = str.indexOf('\n', end + 1)
if (end === -1) {
end = str.length - 1
} else {
end = str.indexOf('\n', end + 1)
if (end === -1) {
end = str.length - 1
}
}
}
const indentSpaces = (new Array(col)).join(' ')
const message = 'Syntax error at line ' + row + ', col ' + col + ': ' + msg
const context = str.substring(start, errorLineEnd) + '\n' + indentSpaces + '^^^^^^^^\n' + str.substring(errorLineEnd + 1, end)
throw new ParseError(message + '\n' + context, context, str, row, col, msg, pos)
}
while (pos < str.length) {
// indentation and comment handling.
if (newline) {
while (newline && pos < str.length) {
let ind = 0
while (str[pos + ind] === ' ' && pos + ind < str.length) {
ind++
}
// if it was an empty content line, then add it to the list of empty
// content to emit on the next non empty line
if (str[pos + ind] === '\n') {
pos += ind + 1
row++
emit('EMPTY_CONTENT', str.substring(start, pos - 1))
} else if (str[pos + ind] !== '#' || consumingUnparsed) {
if (ind > indent[indent.length - 1]) {
emit('INDENT', ind - indent[indent.length - 1])
indent.push(ind)
} else if (ind < indent[indent.length - 1]) {
while (indent[indent.length - 1] > ind) {
const prev = indent.pop()
emit('DEDENT', prev - indent[indent.length - 1])
if (consumingUnparsed && unparsedIndentStart >= indent[indent.length - 1]) {
consumingUnparsed = false
}
}
if (indent.length > 0 && (indent[indent.length - 1] !== ind)) {
err('indentation mismatch: this line dedents with an indentation of ' + ind + ' spaces, but an indentation of ' + indent[indent.length - 1] + ' spaces was expected')
}
}
pos += ind
if (str[pos] === '\\' && str[pos + 1] === '#') {
pos++
}
newline = false
} else {
while (str[pos] !== '\n' && pos < str.length) {
pos++
}
emit('COMMENT', str.substring(start + ind + 1, pos))
pos++
row++
}
start = pos
}
}
if (pos >= str.length) {
return tokens
}
const s = str[pos]
if (state === TYPE) {
if (s === ' ') {
consume('TYPE', PARAMS)
while (shuffleIfNext(' ') && pos < str.length) {}
} else if (s === ':') {
consume('TYPE', CONTENT)
shuffleIfNext(' ')
consumingSameLineContent = true
emit('START_SAME_LINE_CONTENT')
} else if (s === '[') {
consume('TYPE', INLINE_CONTENT)
emit('START_INLINE_CONTENT')
} else if (s === '(') {
consume('TYPE', INLINE_PARAMS)
} else if (s === '\n') {
consume('TYPE', CONTENT)
if (consumingSameLineContent) {
emit('END_SAME_LINE_CONTENT')
consumingSameLineContent = false
}
}
} else if (state === PARAMS) {
if (s === '[') {
escapedParamCounter++
consumingEscapedParams = true
} else if (consumingEscapedParams && (s === ']')) {
escapedParamCounter--
if (escapedParamCounter === 0) {
consumingEscapedParams = false
}
} else if (s === ':' && !consumingEscapedParams) {
consume('PARAMS', CONTENT)
shuffleIfNext(' ')
shuffleIfNext(']')
consumingSameLineContent = true
emit('START_SAME_LINE_CONTENT')
} else if (s === '\n') {
escapedParamCounter = 0
consumingEscapedParams = false
consume('PARAMS', CONTENT)
if (consumingSameLineContent) {
emit('END_SAME_LINE_CONTENT')
consumingSameLineContent = false
}
}
} else if (state === CONTENT) {
if (s === '@' && !consumingUnparsed) {
consumeIfNonEmpty('CONTENT', TYPE)
if (str[pos + 1] === '@') {
consumingUnparsed = true
unparsedIndentStart = indent[indent.length - 1]
pos++
start++
}
} else if (s === '\n') {
if (consumingSameLineContent) {
if (lastInlineContentEndPos !== pos - 1) {
consumeIfNonEmpty('CONTENT', CONTENT)
}
emit('END_SAME_LINE_CONTENT')
consumingSameLineContent = false
consumingUnparsed = false
} else {
if (lastInlineContentEndPos !== pos - 1) {
consumeIfNonEmpty('CONTENT', CONTENT)
}
}
}
} else if (state === INLINE_PARAMS) {
if (s === ')') {
if (str[pos + 1] === '[') {
consume('PARAMS', INLINE_CONTENT)
emit('START_INLINE_CONTENT')
start++
pos++
} else {
consume('PARAMS', CONTENT)
}
}
} else { // if (state === INLINE_CONTENT) {
if (s === '\\' && (str[pos + 1] === '[' || str[pos + 1] === ']')) {
pos++
} else if (s === '[') {
escapedInlineCounter++
} else if (s === ']') {
if (escapedInlineCounter === 0) {
consumeIfNonEmpty('CONTENT', CONTENT, ['\\]', '\\['])
emit('END_INLINE_CONTENT')
lastInlineContentEndPos = pos + 1
} else {
escapedInlineCounter--
}
} else if (s === '\n') {
consume('CONTENT', INLINE_CONTENT)
}
}
if (s === '\n') {
col = 0
row++
newline = true
} else {
col++
}
pos++
}
if (state === TYPE) {
emit('TYPE', str.substring(start, pos))
} else if (state === PARAMS) {
emit('PARAMS', str.substring(start, pos))
} else if (state === INLINE_PARAMS) {
err('missing closing ) bracket?')
} else if (state === INLINE_CONTENT) {
err('missing closing ] bracket?')
} else { // if (state === CONTENT) {
if (start < pos) {
emit('CONTENT', str.substring(start, pos))
}
}
return tokens
}
|
javascript
|
{
"resource": ""
}
|
q8124
|
simple
|
train
|
function simple() {
var recipe, configs;
recipe = recipes.inline(taskInfo) || recipes.plugin(taskInfo) || recipes.task(taskInfo);
if (recipe) {
configs = Configuration.sort(taskInfo, rawConfig, parentConfig, recipe.schema);
if (!configs.taskInfo.name) {
configs.taskInfo.visibility = CONSTANT.VISIBILITY.HIDDEN;
}
return self.create(prefix, configs.taskInfo, configs.taskConfig, recipe);
}
}
|
javascript
|
{
"resource": ""
}
|
q8125
|
auxiliary
|
train
|
function auxiliary() {
var recipe, configs, tasks;
recipe = recipes.stream(taskInfo) || recipes.flow(taskInfo);
if (recipe) {
configs = Configuration.sort(taskInfo, rawConfig, parentConfig, recipe.schema);
if (configs.taskInfo.name !== 'watch' && (!configs.taskInfo.name || !('visibility' in configs.taskInfo))) {
configs.taskInfo.visibility = CONSTANT.VISIBILITY.HIDDEN;
configs.taskInfo.name = '<' + configs.taskInfo.name + '>';
}
tasks = createTasks(configs);
return self.create(prefix, configs.taskInfo, configs.taskConfig, recipe, tasks);
}
}
|
javascript
|
{
"resource": ""
}
|
q8126
|
composite
|
train
|
function composite() {
var configs, type, recipe, tasks, wrapper;
configs = Configuration.sort(taskInfo, rawConfig, parentConfig);
tasks = configs.taskInfo.parallel || configs.taskInfo.series || configs.taskInfo.task || configs.subTaskConfigs;
type = _type();
if (type) {
tasks = createTasks(configs);
recipe = recipes.flow({ recipe: type });
wrapper = self.create(prefix, {
name: '<' + type + '>',
visibility: CONSTANT.VISIBILITY.HIDDEN
}, configs.taskConfig, recipe, tasks);
if (configs.taskInfo.name) {
return self.create(prefix, configs.taskInfo, configs.taskConfig, wrapper, [wrapper]);
}
configs.taskInfo.visibility = CONSTANT.VISIBILITY.HIDDEN;
return wrapper;
}
if (_forward()) {
tasks = createTasks(configs);
recipe = function (done) {
return tasks[0].call(this, done);
};
return self.create(prefix, configs.taskInfo, configs.taskConfig, recipe, tasks);
}
function _type() {
if (configs.taskInfo.series) {
return 'series';
} else if (configs.taskInfo.parallel) {
return 'parallel';
} else if (_.size(tasks) > 1) {
if (Array.isArray(tasks)) {
return 'series';
} else if (_.isPlainObject(tasks)) {
return 'parallel';
}
}
}
function _forward() {
return _.size(tasks) === 1;
}
}
|
javascript
|
{
"resource": ""
}
|
q8127
|
train
|
function(port, options) {
var stream = new SimpleStream();
var prompt = 'node> ';
var rs = repl.start({ prompt: prompt, input: stream, output: stream});
var replHttpServer = new ReplHttpServer(prompt, stream, rs, options);
replHttpServer.start(port);
return rs;
}
|
javascript
|
{
"resource": ""
}
|
|
q8128
|
train
|
function(context) {
this._context = context;
if (this.scenes) {
_.each(this.scenes, function(scene) {
scene.setContext(context);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8129
|
leaf_to
|
train
|
function leaf_to( sceneName, argsArr, deferred ) {
this._transitioning = true;
var complete = this._complete = deferred || _.Deferred(),
args = argsArr ? argsArr : [],
handlerComplete = _.Deferred()
.done(_.bind(function() {
this._transitioning = false;
this._current = sceneName;
complete.resolve();
}, this))
.fail(_.bind(function() {
this._transitioning = false;
complete.reject();
}, this));
this.handlers[sceneName].call(this._context, args, handlerComplete);
return complete.promise();
}
|
javascript
|
{
"resource": ""
}
|
q8130
|
train
|
function(hcExportRequest,asyncCallback){
var makeThisExportDir = function(mkExportDirErr){
var thisExportDir = [config.processingDir, crypto.createHash('md5').update(Date().toString()+hcExportRequest.svg).digest('hex'),''].join('/');
fs.mkdir(thisExportDir, function(error){
asyncCallback(mkExportDirErr, thisExportDir, hcExportRequest);
});
};
if(fs.existsSync(config.processingDir)){
makeThisExportDir(null);
}
else{
fs.mkdir(config.processingDir, function(error){
makeThisExportDir(error);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8131
|
train
|
function(processingDir, hcExportRequest, callback){
var outputChartName = hcExportRequest.filename,
outputFormat = hcExportRequest.type.split('/')[1],
outputExtension = outputFormat == 'svg+xml' ? '.svg' : '.' + outputFormat,
outputFile = outputChartName + outputExtension,
outputFilePath = processingDir + outputFile,
basePNGFile = processingDir + outputChartName + '.png',
baseSVGFile = processingDir + outputChartName + '.svg',
exportInfo = {
fileName : outputChartName,
file : outputFile,
type : outputExtension.replace('.',''),
parentDir : processingDir,
filePath : outputFilePath
};
fs.writeFile(baseSVGFile, hcExportRequest.svg, function(svgErr){
if(outputFormat == 'svg+xml'){
callback(null, exportInfo);
}
else{
svg2png(baseSVGFile, basePNGFile, hcExportRequest.scale, function(err){
switch(outputFormat){
case 'png':
callback(null, exportInfo);
break;
case 'pdf':
var pdf = new pdfkit({size:'A4',layout:'landscape'});
pdf.image(basePNGFile,{width : 700})
.write(outputFilePath, function(){
callback(null, exportInfo);
});
break;
case 'jpeg':
case 'jpg':
jpegConvert(basePNGFile, outputFilePath , {width : 1200}, function(jpegError){
if(jpegError) throw jpegError;
callback(null,exportInfo);
});
break;
default:
var errorMessage = ['Invalid export format requested:',outputFormat+'.','Currently supported outputFormats: svg+xml, pdf, jpeg, jpg, and png.'].join(' ');
callback({message: errorMessage}, null);
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8132
|
num_of_cpus
|
train
|
function num_of_cpus() {
try {
if(process.env['OMP_NUM_THREADS']) {
return process.env['OMP_NUM_THREADS'];
}
return Math.ceil(jsonConfig.info.limits.cpu);
} catch (err) {
throw new Error('Could not get number of cpus');
}
}
|
javascript
|
{
"resource": ""
}
|
q8133
|
config
|
train
|
function config() {
if(!process.env.PLATFORM_PROJECT) {
throw Error('This is not running on platform.sh');
}
return {
application: read_base64_json('PLATFORM_APPLICATION'),
relationships: read_base64_json('PLATFORM_RELATIONSHIPS'),
variables: read_base64_json('PLATFORM_VARIABLES'),
application_name: process.env.PLATFORM_APPLICATION_NAME,
app_dir: process.env.PLATFORM_APP_DIR,
environment: process.env.PLATFORM_ENVIRONMENT,
project: process.env.PLATFORM_PROJECT,
routes: read_base64_json('PLATFORM_ROUTES'),
tree_id: process.env.PLATFORM_TREE_ID,
project_entropy: process.env.PLATFORM_PROJECT_ENTROPY,
branch: process.env.PLATFORM_BRANCH,
document_root: process.env.PLATFORM_DOCUMENT_ROOT,
port: process.env.PORT,
omp_num_threads: num_of_cpus()
};
}
|
javascript
|
{
"resource": ""
}
|
q8134
|
StaticEndpoint
|
train
|
function StaticEndpoint(properties) {
this.headers = {};
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q8135
|
StaticWebsite
|
train
|
function StaticWebsite(properties) {
this.endpoints = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q8136
|
transform
|
train
|
function transform(transform, flush) {
const stream = new Transform({ objectMode: true });
stream._transform = transform;
if (typeof flush === 'function') {
stream._flush = flush;
}
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q8137
|
findInstance
|
train
|
function findInstance(state, stateKey, instanceKey, payload) {
return state[stateKey].find(obj => obj[instanceKey] === payload[instanceKey]);
}
|
javascript
|
{
"resource": ""
}
|
q8138
|
findValue
|
train
|
function findValue(payload, instanceKey) {
for (let key in payload) {
if (key !== instanceKey) {
return payload[key];
}
}
// if we don't have a value, throw an error because the payload is invalid.
/* istanbul ignore next */
throw new Error('Failed to mutate instance, no value found in payload.', payload);
}
|
javascript
|
{
"resource": ""
}
|
q8139
|
train
|
function( maxId, callback ) {
if( typeof maxId === 'function' ) {
callback = maxId
maxId = null
}
var self = this
var id = maxId ? '/' + maxId : ''
return this.client._clientRequest({
url: '/alerts/rest/v1/json/list' + id,
}, function( error, data ) {
callback.call( self.client, error, data )
})
}
|
javascript
|
{
"resource": ""
}
|
|
q8140
|
train
|
function( id, callback ) {
var self = this
return this.client._clientRequest({
url: '/alerts/rest/v1/json/get/' + id,
}, function( error, data ) {
callback.call( self.client, error, data )
})
}
|
javascript
|
{
"resource": ""
}
|
|
q8141
|
train
|
function( options, callback ) {
var self = this
var path = '/alerts/rest/v1/json/testdelivery/' +
options.airlineCode + '/' + options.flightNumber +
'/from/' + options.departureAirport +
'/to/' + options.arrivalAirport
var extensions = [
'includeNewFields',
'useInlinedReferences'
]
if( Array.isArray( options.extendedOptions ) ) {
extensions = extensions.concat( options.extendedOptions )
}
return this.client._clientRequest({
url: path,
extendedOptions: extensions,
qs: {
deliverTo: options.deliverTo,
type: options.type || 'JSON',
},
}, function( error, data ) {
callback.call( self.client, error, data )
})
}
|
javascript
|
{
"resource": ""
}
|
|
q8142
|
train
|
function( options, callback ) {
var self = this
var events = options.events || [ 'all' ]
var year = options.date.getFullYear()
var month = options.date.getMonth() + 1
var day = options.date.getDate()
var direction = /^dep/i.test( options.direction ) ?
'departing' : 'arriving'
var path = '/alerts/rest/v1/json/create/' +
options.airlineCode + '/' + options.flightNumber +
'/from/' + options.departureAirport +
'/to/' + options.arrivalAirport +
'/' + direction + '/' + year + '/' + month + '/' + day
var extensions = [
'includeNewFields',
'useInlinedReferences'
]
if( Array.isArray( options.extendedOptions ) ) {
extensions = extensions.concat( options.extendedOptions )
}
var query = {
name: options.name,
desc: options.desc,
codeType: options.codeType,
events: events.join(),
deliverTo: options.deliverTo,
type: options.type || 'JSON',
}
// Add underscore-prefixed custom data
// key-value pairs to query parameters
if( options.data != null ) {
Object.keys( options.data ).forEach( function( k ) {
query[ '_' + k ] = options.data[k]
})
}
return this.client._clientRequest({
url: path,
extendedOptions: extensions,
qs: query,
}, function( error, data ) {
callback.call( self.client, error, data )
})
}
|
javascript
|
{
"resource": ""
}
|
|
q8143
|
csvFieldNames
|
train
|
function csvFieldNames (inFields) {
const fieldNames = _.map(inFields, (field) => {
return convertFieldName(field)
})
return fieldNames
}
|
javascript
|
{
"resource": ""
}
|
q8144
|
convertCSVGeom
|
train
|
function convertCSVGeom (columns, row) {
const geometry = _.reduce(columns, (tempGeom, colName, i) => {
if (isLongitudeField(colName)) tempGeom.coordinates[0] = parseFloat(row[i])
else if (isLatitudeField(colName)) tempGeom.coordinates[1] = parseFloat(row[i])
return tempGeom
}, { type: 'Point', coordinates: [null, null] })
return validGeometry(geometry) ? geometry : null
}
|
javascript
|
{
"resource": ""
}
|
q8145
|
validGeometry
|
train
|
function validGeometry (geometry) {
return geometry.coordinates.length === 2 && (geometry.coordinates[0] && geometry.coordinates[1]) ? true : false
}
|
javascript
|
{
"resource": ""
}
|
q8146
|
constructProps
|
train
|
function constructProps (fieldNames, feature) {
const properties = _.reduce(fieldNames, (tempProps, fieldName, key) => {
tempProps[fieldName] = (!isNaN(feature[key])) ? parseFloat(feature[key]) : feature[key]
return tempProps
}, {})
return properties
}
|
javascript
|
{
"resource": ""
}
|
q8147
|
convertFields
|
train
|
function convertFields (infields) {
const fields = {}
_.each(infields, (field) => {
field.outName = convertFieldName(field.name)
fields[field.name] = field
})
return fields
}
|
javascript
|
{
"resource": ""
}
|
q8148
|
convertFieldName
|
train
|
function convertFieldName (name) {
const regex = new RegExp(/\.|\(|\)/g)
return name.replace(regex, '').replace(/\s/g, '_')
}
|
javascript
|
{
"resource": ""
}
|
q8149
|
transformFeature
|
train
|
function transformFeature (feature, fields) {
const attributes = {}
// first transform each of the features to the converted field name and transformed value
if (feature.attributes && Object.keys(feature.attributes)) {
_.each(Object.keys(feature.attributes), (name) => {
let attr = {}
attr[name] = feature.attributes[name]
try {
attributes[fields[name].outName] = convertAttribute(attr, fields[name])
} catch (e) {
console.error('Field was missing from attribute')
}
})
}
return {
type: 'Feature',
properties: attributes,
geometry: parseGeometry(feature.geometry)
}
}
|
javascript
|
{
"resource": ""
}
|
q8150
|
convertAttribute
|
train
|
function convertAttribute (attribute, field) {
const inValue = attribute[field.name]
let value
if (inValue === null) return inValue
if (field.domain && field.domain.type === 'codedValue') {
value = cvd(inValue, field)
} else if (field.type === 'esriFieldTypeDate') {
try {
value = new Date(inValue).toISOString()
} catch (e) {
value = inValue
}
} else {
value = inValue
}
return value
}
|
javascript
|
{
"resource": ""
}
|
q8151
|
cvd
|
train
|
function cvd (value, field) {
const domain = _.find(field.domain.codedValues, (d) => {
return value === d.code
})
return domain ? domain.name : value
}
|
javascript
|
{
"resource": ""
}
|
q8152
|
parseGeometry
|
train
|
function parseGeometry (geometry) {
try {
const parsed = geometry ? arcgisToGeoJSON(geometry) : null
if (parsed && parsed.type && parsed.coordinates) return parsed
else {
return null
}
} catch (e) {
console.error(e)
return null
}
}
|
javascript
|
{
"resource": ""
}
|
q8153
|
createSetter
|
train
|
function createSetter(namespace, mappings) {
let mutation = mappings.mutation;
if (namespace) {
mutation = namespace + '/' + mutation;
}
return function (value) {
this.$store.commit(mutation, value)
};
}
|
javascript
|
{
"resource": ""
}
|
q8154
|
disabledRules
|
train
|
function disabledRules(directives) {
return directives.reduce((disabled, _ref) => {
let name = _ref.name;
let args = _ref.args;
if (name === 'bplint-disable') {
for (const ruleName of args) {
disabled[ruleName] = true;
}
} else if (name === 'bplint-enable') {
for (const ruleName of args) {
if (disabled[ruleName]) {
disabled[ruleName] = false;
}
}
}
return disabled;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q8155
|
decode
|
train
|
function decode(str) {
let off = 0;
let olen = 0;
const slen = str.length;
const stra = [];
const len = str.length;
while (off < slen - 1 && olen < len) {
let code = str.charCodeAt(off++);
const c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
code = str.charCodeAt(off++);
const c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
if (c1 === -1 || c2 === -1) break;
let o = (c1 << 2) >>> 0;
o |= (c2 & 0x30) >> 4;
stra.push(String.fromCharCode(o));
if (++olen >= len || off >= slen) break;
code = str.charCodeAt(off++);
const c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
if (c3 === -1) break;
o = ((c2 & 0x0f) << 4) >>> 0;
o |= (c3 & 0x3c) >> 2;
stra.push(String.fromCharCode(o));
if (++olen >= len || off >= slen) break;
code = str.charCodeAt(off++);
const c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
o = ((c3 & 0x03) << 6) >>> 0;
o |= c4;
stra.push(String.fromCharCode(o));
++olen;
}
const buffa = [];
for (off = 0; off < olen; off++) buffa.push(stra[off].charCodeAt(0));
return Buffer.from(buffa);
}
|
javascript
|
{
"resource": ""
}
|
q8156
|
midi
|
train
|
function midi (instrument, options) {
options = options || {}
var midi = {}
var unused = []
instrument.names().forEach(function (name) {
var m = toMidi(name)
if (m) midi[m] = instrument.get(name)
else unused.push(name)
})
if (options.map) addMap(midi, instrument, options.map)
return {
unused: function () { return unused.slice() },
names: function () { return Object.keys(midi) },
get: function (name) { return midi[toMidi(name) || name] }
}
}
|
javascript
|
{
"resource": ""
}
|
q8157
|
sort
|
train
|
function sort(taskInfo, rawConfig, parentConfig, optionalSchema) {
var schema, subTaskConfigs, taskConfig, value;
schema = optionalSchema || {};
from(schema).to(taskInfo).imply(TASK_SCHEMA_MAPPINGS);
schema = defaults({}, schema, SCHEMA_DEFAULTS);
taskConfig = rawConfig;
// NOTE: If schema provided, try to normalize properties inside 'config' property.
if (optionalSchema) {
taskConfig = regulate(taskConfig, ['config']);
}
taskConfig = normalize(schema, taskConfig, {
before: before,
after: after
});
taskConfig = renamePatternProperties(taskConfig);
// NOTE: A thought about that `config` should be "normalized".
// But remember that the `config` and `$` property prefix are designed for tasks that have no schemas.
// It just won't do anything try to normalize it without schema.
taskConfig = regulate(taskConfig, ['config']);
// NOTE: When there is `plugin`, `task`, `series` or `parallel` property,
// then all other properties will be treated as properties, not sub-task configs.
// So user don't have to use `config` keyword or `$` prefix.
value = _.omit(rawConfig, Object.keys(taskConfig).concat('config'));
if (!optionalSchema && (taskInfo.plugin || taskInfo.task || taskInfo.series || taskInfo.parallel)) {
taskConfig = defaults(taskConfig, value);
} else {
subTaskConfigs = value;
}
// inherit parent's config
taskConfig = defaults(taskConfig, parentConfig);
return {
taskInfo: taskInfo,
taskConfig: taskConfig,
subTaskConfigs: subTaskConfigs
};
function before(propSchema, values) {
if (propSchema.type === 'glob') {
_.defaults(propSchema, glob.SCHEMA);
} else if (propSchema.type === 'path') {
_.defaults(propSchema, path.SCHEMA);
}
}
function after(propSchema, resolved) {
var value, join;
if (resolved) {
value = resolved();
if (propSchema.type === 'glob') {
join = propSchema.properties.options.properties.join.default || 'src';
return resolve(resolveSrc(parentConfig, value, join));
} else if (propSchema.type === 'path') {
join = propSchema.properties.options.properties.join.default || 'dest';
return resolve(resolveDest(parentConfig, value, join));
}
}
return resolved;
function resolve(value) {
return function () {
return value;
};
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8158
|
createElement
|
train
|
function createElement (tagName) {
if (!tagName || tagName.length < 1) return new infer.Obj(infer.def.parsePath('HTMLElement.prototype'))
var cx = infer.cx(), server = cx.parent, name = getHTMLElementName(tagName),
locals = infer.def.parsePath(name + '.prototype')
if (locals && locals != infer.ANull) return new infer.Obj(locals)
return createElement()
}
|
javascript
|
{
"resource": ""
}
|
q8159
|
findTypeAt
|
train
|
function findTypeAt (_file, _pos, expr, type) {
if (!expr) return type
var isStringLiteral = expr.node.type === 'Literal' &&
typeof expr.node.value === 'string'
if (isStringLiteral) {
var attr = null
if (!!expr.node.dom) {
attr = expr.node.dom
} else if (!!expr.node.eventType) {
var eventType = expr.node.eventType
type = Object.create(type)
type.doc = eventType['!doc']
type.url = eventType['!url']
type.origin = "browser-extension"
} else if (expr.node.cssselectors == true) {
var text = _file.text, wordStart = _pos, wordEnd = _pos
while (wordStart && acorn.isIdentifierChar(text.charCodeAt(wordStart - 1))) --wordStart
while (wordEnd < text.length && acorn.isIdentifierChar(text.charCodeAt(wordEnd))) ++wordEnd
var id = text.slice(wordStart, wordEnd)
attr = getAttr(expr.node, id)
}
if (attr) {
// The `type` is a value shared for all string literals.
// We must create a copy before modifying `origin` and `originNode`.
// Otherwise all string literals would point to the last jump location
type = Object.create(type)
type.origin = attr.sourceFile.name
type.originNode = attr
}
}
return type
}
|
javascript
|
{
"resource": ""
}
|
q8160
|
hash
|
train
|
function hash(password, options) {
options = options || {};
const rounds = options.rounds || defaults.rounds;
const saltSize = options.saltSize || defaults.saltSize;
const version = versions[versions.length - 1];
// Rounds Validation
if (typeof rounds !== 'number' || !Number.isInteger(rounds)) {
return Promise.reject(
new TypeError("The 'rounds' option must be an integer")
);
}
if (rounds < 4 || rounds > 31) {
return Promise.reject(
new TypeError(
`The 'rounds' option must be in the range (4 <= rounds <= 31)`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)"
)
);
}
return gensalt(saltSize).then(salt => {
const bb64salt = bb64.encode(salt);
const padrounds = rounds > 9 ? Number(rounds) : '0' + rounds;
const decver = String.fromCharCode(version);
const parstr = `$2${decver}$${padrounds}$${bb64salt}`;
return bcrypt.hash(password, parstr).then(enchash => {
const hash = bb64.decode(enchash.split(parstr)[1]);
const phcstr = phc.serialize({
id: 'bcrypt',
version,
params: {
r: rounds
},
salt,
hash
});
return phcstr;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q8161
|
formatLine
|
train
|
function formatLine({ rule, message, location }, metrics) {
const { line, col } = location;
const { line: lineW, col: colW, message: msgW } = metrics;
const loc = sprintf(`%${lineW}d:%-${colW}d`, line, col);
const msg = sprintf(`%-${msgW}s`, message);
return ` ${loc} ${msg} ${rule}`;
}
|
javascript
|
{
"resource": ""
}
|
q8162
|
prepareTransforms
|
train
|
function prepareTransforms (entityTransforms, namespace, target) {
const resolvedNamespace = namespace || ''
const resolvedTarget = target || {}
for (const d in entityTransforms) {
if (typeof (entityTransforms[d]) === 'function') {
resolvedTarget[resolvedNamespace + d] = entityTransforms[d]
resolvedTarget[d] = entityTransforms[d]
} else {
prepareTransforms(entityTransforms[d], resolvedNamespace + d + '.', resolvedTarget)
}
}
return resolvedTarget
}
|
javascript
|
{
"resource": ""
}
|
q8163
|
transformer
|
train
|
function transformer (selection) {
const type = quantum.isSelection(selection) ? selection.type() : undefined
const entityTransform = transformMap[type] || defaultTransform
return entityTransform(selection, transformer, meta) // bootstrap to itself to make the transformer accessible to children
}
|
javascript
|
{
"resource": ""
}
|
q8164
|
Error
|
train
|
function Error() {
Illuminati.apply(this, arguments);
var backtrace = new Backtrace({ error: this })
, sourcemap = stackmap(Error.sourcemap).map(backtrace.traces);
this.stringify(backtrace.traces, sourcemap);
}
|
javascript
|
{
"resource": ""
}
|
q8165
|
getKeys
|
train
|
function getKeys(definition){
return definition.provides.map(function(component){
return definition.package + '/' + component;
}).concat(getPrimaryKey(definition));
}
|
javascript
|
{
"resource": ""
}
|
q8166
|
getProjectName
|
train
|
function getProjectName(componentPath, optionsName){
if (typeof optionsName == 'string') return optionsName;
var projectName;
for (var prj in optionsName){
if(~componentPath.indexOf(optionsName[prj])) projectName = prj;
}
if (!projectName) grunt.fail.warn('Missing name in options for component with path: ' + componentPath);
return projectName;
}
|
javascript
|
{
"resource": ""
}
|
q8167
|
toArray
|
train
|
function toArray(object){
if (!object) return [];
if (object.charAt) return [object];
return grunt.util.toArray(object);
}
|
javascript
|
{
"resource": ""
}
|
q8168
|
checkRegistry
|
train
|
function checkRegistry(registry, key, path){
if (registry[key] == undefined){
throw new Error('Dependency not found: ' + key + ' in ' + path);
}
}
|
javascript
|
{
"resource": ""
}
|
q8169
|
findInstanceThen
|
train
|
function findInstanceThen() {
// this function supports two argument signatures. if the
// first argument is an object, we will use that as the
// config, and the second arg as the mutation handler
var _parseArguments = parseArguments(arguments),
config = _parseArguments.config,
callback = _parseArguments.callback;
return function (state, payload) {
if (stateAndPayloadAreValid(config, state, payload)) {
// find our instance based on the current configuration
var instance = state[config.stateKey].find(function (obj) {
return obj[config.instanceKey] === payload[config.instanceKey];
});
// if the instance was found, execute our mutation callback
if (instance) {
callback(instance, payload, state);
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q8170
|
parseArguments
|
train
|
function parseArguments(args) {
var defaultConfig = {
stateKey: 'instances',
instanceKey: 'id'
};
if (typeof args[0] === 'function') {
return {
callback: args[0],
config: defaultConfig
};
} else {
return {
callback: args[1],
config: Object.assign({}, defaultConfig, args[0])
};
}
}
|
javascript
|
{
"resource": ""
}
|
q8171
|
stateAndPayloadAreValid
|
train
|
function stateAndPayloadAreValid(config, state, payload) {
// ensure that the instances array exists
if (!Array.isArray(state[config.stateKey])) {
console.error('State does not contain an "' + config.stateKey + '" array.');
return false;
}
// ensure that the payload contains an id
if ((typeof payload === 'undefined' ? 'undefined' : _typeof(payload)) !== 'object' || typeof payload[config.instanceKey] === 'undefined') {
console.error('Mutation payloads must be an object with an "' + config.instanceKey + '" property.');
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q8172
|
instance_getters
|
train
|
function instance_getters () {
var _parseArguments = parseArguments$1(arguments),
getters = _parseArguments.getters,
options = _parseArguments.options;
return Object.keys(getters).reduce(function (instanceGetters, name) {
instanceGetters[name] = function (state, otherGetters) {
return function (instanceKey) {
var instance = state[options.stateKey || 'instances'].find(function (obj) {
return obj[options.instanceKey || 'id'] === instanceKey;
});
if (instance) {
return getters[name](instance, otherGetters, state, instanceKey);
}
};
};
return instanceGetters;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q8173
|
instance_mutations
|
train
|
function instance_mutations () {
var _parseArguments = parseArguments$2(arguments),
options = _parseArguments.options,
mutations = _parseArguments.mutations;
return Object.keys(mutations).reduce(function (instanceMutations, name) {
instanceMutations[name] = findInstanceThen(options, mutations[name]);
return instanceMutations;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q8174
|
getEntries
|
train
|
function getEntries (obj) {
return Object.keys(obj).map(function (key) {
return [key, obj[key]];
});
}
|
javascript
|
{
"resource": ""
}
|
q8175
|
wrapGetterFn
|
train
|
function wrapGetterFn(_ref) {
var _ref2 = slicedToArray(_ref, 2),
key = _ref2[0],
originalFn = _ref2[1];
var newFn = function newFn() {
var innerFn = originalFn.apply(this, arguments);
if (typeof innerFn !== 'function') {
/* istanbul ignore next */
throw 'The getter ' + key + ' does not return a function. Try using the \'mapGetter\' helper instead';
}
return innerFn(this.id);
};
return [key, newFn];
}
|
javascript
|
{
"resource": ""
}
|
q8176
|
resolveObjectPath
|
train
|
function resolveObjectPath (obj, path) {
var delimeter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
var pathArray = Array.isArray(path) ? path : path.split(delimeter);
return pathArray.reduce(function (p, item) {
return p && p[item];
}, obj);
}
|
javascript
|
{
"resource": ""
}
|
q8177
|
normalizeMappings
|
train
|
function normalizeMappings(mappings) {
if (Array.isArray(mappings)) {
return mappings.reduce(function (normalizedMappings, key) {
normalizedMappings[key] = key;
return normalizedMappings;
}, {});
}
return mappings;
}
|
javascript
|
{
"resource": ""
}
|
q8178
|
error
|
train
|
function error (message) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
throw new (Function.prototype.bind.apply(Error, [null].concat(['[spyfu-vuex-helpers]: ' + message], args)))();
}
|
javascript
|
{
"resource": ""
}
|
q8179
|
map_two_way_state
|
train
|
function map_two_way_state () {
// this function supports two argument signatures. if the
// first argument is a string, we will use that as the
// namespace, and the next arg as the state mapping
var _parseArguments = parseArguments$3(arguments),
namespace = _parseArguments.namespace,
mappings = _parseArguments.mappings;
// then get the key and mutation names from our mappings
var parsedMappings = parseMappings(mappings);
// and last, turn them into getters and setters
var computedProperties = {};
Object.keys(parsedMappings).forEach(function (key) {
computedProperties[key] = {
get: createGetter$1(namespace, parsedMappings[key]),
set: createSetter(namespace, parsedMappings[key])
};
});
return computedProperties;
}
|
javascript
|
{
"resource": ""
}
|
q8180
|
parseMappings
|
train
|
function parseMappings(obj) {
var mapping = {};
// throw a helpful error when mapTwoWayState is mixed up with mapState
if (Array.isArray(obj)) {
error('Invalid arguments for mapTwoWayState. State mapping must be an object in { \'path.to.state\': \'mutationName\' } format.');
}
Object.keys(obj).forEach(function (key) {
var value = obj[key];
var vmKey = key.slice(key.lastIndexOf('.') + 1);
if (typeof value === 'string') {
mapping[vmKey] = { key: key, mutation: value };
} else {
mapping[vmKey] = { key: value.key, mutation: value.mutation };
}
});
return mapping;
}
|
javascript
|
{
"resource": ""
}
|
q8181
|
simple_instance_setters
|
train
|
function simple_instance_setters (setters) {
var stateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'instances';
var instanceKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'id';
// loop over the setter keys and make a mutation for each
return Object.keys(setters).reduce(function (mutations, name) {
// attach our new mutation to result
return Object.assign({}, mutations, defineProperty({}, name, function (state, payload) {
// find the instance that we're mutating
var instance = findInstance(state, stateKey, instanceKey, payload);
if (instance) {
var value = findValue(payload, instanceKey);
// if the setter name has a dot, then resolve the
// state path before feeding our value into it.
if (setters[name].indexOf('.') > -1) {
var obj = setters[name].split('.');
var key = obj.pop();
resolveObjectPath(instance, obj)[key] = value;
} else {
// otherwise, just set the instance state to our value
instance[setters[name]] = value;
}
} else {
// if the instance wasn't found, let the dev know with a warning
console.warn('An instance with an identifier of ' + instanceKey + ' was not found.');
}
}));
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q8182
|
simple_setters
|
train
|
function simple_setters (setters) {
// loop over the setter keys and make a mutation for each
return Object.keys(setters).reduce(function (mutations, name) {
// attach our new mutation to result
return Object.assign({}, mutations, defineProperty({}, name, function (state, value) {
// if the setter name has a dot, then resolve the
// state path before feeding our value into it.
if (setters[name].indexOf('.') > -1) {
var obj = setters[name].split('.');
var key = obj.pop();
resolveObjectPath(state, obj)[key] = value;
}
// otherwise, just set the state to our value
else state[setters[name]] = value;
}));
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q8183
|
train
|
function(event) {
event = event || window.event;
self.state = count++ ? "change" : "start";
self.wheelDelta = event.detail ? event.detail * -20 : event.wheelDelta;
conf.listener(event, self);
clearTimeout(interval);
interval = setTimeout(function() {
count = 0;
self.state = "end";
self.wheelDelta = 0;
conf.listener(event, self);
}, timeout);
}
|
javascript
|
{
"resource": ""
}
|
|
q8184
|
getType
|
train
|
function getType (str, typeLinks) {
if (str in typeLinks) {
return dom.create('a').class('qm-api-type-link').attr('href', typeLinks[str]).text(str)
} else {
return str
}
}
|
javascript
|
{
"resource": ""
}
|
q8185
|
children_to
|
train
|
function children_to( sceneName, argsArr, deferred ) {
var toScene = this.scenes[sceneName],
fromScene = this._current,
args = argsArr ? argsArr : [],
complete = this._complete = deferred || _.Deferred(),
exitComplete = _.Deferred(),
enterComplete = _.Deferred(),
publish = _.bind(function(name, isExit) {
var sceneName = isExit ? fromScene : toScene;
sceneName = sceneName ? sceneName.name : "";
this.publish(name, fromScene, toScene);
if (name !== "start" || name !== "end") {
this.publish(sceneName + ":" + name);
}
}, this),
bailout = _.bind(function() {
this._transitioning = false;
this._current = fromScene;
publish("fail");
complete.reject();
}, this),
success = _.bind(function() {
publish("enter");
this._transitioning = false;
this._current = toScene;
publish("end");
complete.resolve();
}, this);
if (!toScene) {
throw "Scene \"" + sceneName + "\" not found!";
}
// we in the middle of a transition?
if (this._transitioning) {
return complete.reject();
}
publish("start");
this._transitioning = true;
if (fromScene) {
// we are coming from a scene, so transition out of it.
fromScene.to("exit", args, exitComplete);
exitComplete.done(function() {
publish("exit", true);
});
} else {
exitComplete.resolve();
}
// when we're done exiting, enter the next set
_.when(exitComplete).then(function() {
toScene.to(toScene._initial || "enter", args, enterComplete);
}).fail(bailout);
enterComplete
.then(success)
.fail(bailout);
return complete.promise();
}
|
javascript
|
{
"resource": ""
}
|
q8186
|
sluggifyText
|
train
|
function sluggifyText (text) {
const slug = unEscapeHtmlTags(text).toLowerCase()
// Replace 'unsafe' chars with dashes (!!!! is changed to -)
.replace(unsafeCharsRegex, '-')
// Replace multiple concurrent dashes with a single dash
.replace(multiDashRegex, '-')
// Remove trailing -
.replace(lastCharDashRegex, '')
// Encode the resulting string to make it url-safe
return encodeURIComponent(slug)
}
|
javascript
|
{
"resource": ""
}
|
q8187
|
dedupeAndSluggify
|
train
|
function dedupeAndSluggify (sluggify) {
const existingHeadings = {}
return (heading) => {
const sluggifiedText = sluggify(heading)
const existingCount = existingHeadings[sluggifiedText] || 0
existingHeadings[sluggifiedText] = existingCount + 1
return existingCount > 0 ? `${sluggifiedText}-${existingCount}` : sluggifiedText
}
}
|
javascript
|
{
"resource": ""
}
|
q8188
|
Client
|
train
|
function Client(name, password) {
if (!(this instanceof Client)) {
return new Client(name, password);
}
this.name = name || 'RETS-Connector1/2';
this.password = password || '';
}
|
javascript
|
{
"resource": ""
}
|
q8189
|
parseNums
|
train
|
function parseNums(obj, options) {
var result = Array.isArray(obj) ? [] : {},
key,
value,
parsedValue;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
value = obj[key];
parsedValue = options.parser.call(null, value, 10, key);
if (typeof value === 'string' && !isNaN(parsedValue)) {
result[key] = parsedValue;
}
else if (value.constructor === Object || Array.isArray(value)) {
result[key] = parseNums(value, options);
}
else {
result[key] = value;
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8190
|
wrapper
|
train
|
function wrapper (fileContent, wrapperOptions) {
const selection = quantum.select({
type: '',
params: [],
content: fileContent.content
})
if (selection.has('template')) {
const template = selection.select('template')
// find out the name of the entity to replace with the page content
const contentEntityType = template.has('contentEntityName') ?
template.select('contentEntityName').ps() : 'content'
// find the place to mount the rest of the page's content
const contentEntity = template.select('content').select(contentEntityType, {recursive: true})
const parentContent = contentEntity.parent().content()
// find out where the mount point is
const position = parentContent.indexOf(contentEntity.entity())
// get the content to place at the mount point (ie remove all @templates from the page)
const nonTemplateContent = selection.filter(x => x.type !== 'template')
// make the replacement
parentContent.splice.apply(parentContent, [position, 1].concat(nonTemplateContent.content()))
return {
content: template.select('content').content()
}
} else {
return fileContent
}
}
|
javascript
|
{
"resource": ""
}
|
q8191
|
readFile
|
train
|
function readFile(e) {
const file = e.currentTarget.files && e.currentTarget.files[0];
const reader = new FileReader();
reader.onload = event => ArtBoard.loadANSI(event.target.result);
if (file) reader.readAsText(file);
}
|
javascript
|
{
"resource": ""
}
|
q8192
|
streamFromString
|
train
|
function streamFromString(string) {
const s = new stream.Readable();
s.push(string);
s.push(null);
return s;
}
|
javascript
|
{
"resource": ""
}
|
q8193
|
share
|
train
|
function share() {
var status = $.trim($('#status').val()),
target = $('#target').val();
// Nothing to share
if(status === '') {
return;
}
// When messaging an individual user, update the target to be the user
// that is being messaged.
if(target === 'user') {
target = $('#target_user').val();
}
// Dispatch the message to the server.
socket.emit('post', status, target);
// Clear the status input for the next message.
$('#status').val('');
}
|
javascript
|
{
"resource": ""
}
|
q8194
|
train
|
function( options, callback ) {
if( typeof options === 'function' ) {
callback = options
options = null
}
options = options != null ? options : {}
var self = this
var baseUrl = 'airlines/rest/v1/json'
var isCode = options.fs || options.iata || options.icao
var supportsDate = !options.all || isCode
if( !options.all && !isCode ) {
baseUrl += '/active'
} else if( !isCode ) {
baseUrl += '/all'
}
if( options.fs ) {
baseUrl += '/fs/' + options.fs
} else if( options.iata ) {
baseUrl += '/iata/' + options.iata
} else if( options.icao ) {
baseUrl += '/icao/' + options.icao
}
if( options.date && supportsDate ) {
var year = options.date.getFullYear()
var month = options.date.getMonth() + 1
var day = options.date.getDate()
baseUrl += '/' + year + '/' + month + '/' + day
}
return this._clientRequest({
url: baseUrl,
extendedOptions: [
'includeNewFields'
],
}, function( error, data ) {
if( error != null )
return callback.call( self, error )
var airlines = [].concat( data.airlines || data.airline || [] )
// Trim excessive whitespace in airline names
airlines.forEach( function( airline ) {
airline.name = airline.name.replace( /^\s|\s$/g, '' )
})
// Expand the airline category to a detailed object
if( options.expandCategory ) {
airlines.forEach( function( airline ) {
var info = FlightStats.AirlineCategory[ airline.category ]
airline.category = {
code: ( info && info.code ) || airline.category,
scheduled: info && info.scheduled,
passenger: info && info.passenger,
cargo: info && info.cargo,
}
})
}
callback.call( self, error, airlines )
})
}
|
javascript
|
{
"resource": ""
}
|
|
q8195
|
train
|
function( options, callback ) {
if( typeof options === 'function' ) {
callback = options
options = null
}
options = options != null ? options : {}
var self = this
var baseUrl = 'airports/rest/v1/json'
var isCode = options.fs || options.iata || options.icao
var isLocationCode = options.city || options.country
var isLocation = options.latitude && options.longitude && options.radius
var supportsDate = !options.all && isCode
if( !options.all && !isCode ) {
baseUrl += '/active'
} else if( !isCode && !isLocationCode && !isLocation ) {
baseUrl += '/all'
}
if( isCode || isLocationCode ) {
if( options.fs ) {
baseUrl += '/fs/' + options.fs
} else if( options.iata ) {
baseUrl += '/iata/' + options.iata
} else if( options.icao ) {
baseUrl += '/icao/' + options.icao
} else if( options.city ) {
baseUrl += '/cityCode/' + options.city
} else if( options.country ) {
baseUrl += '/countryCode/' + options.country
}
}
if( options.date && supportsDate ) {
var year = options.date.getFullYear()
var month = options.date.getMonth() + 1
var day = options.date.getDate()
baseUrl += '/' + year + '/' + month + '/' + day
}
if( isLocation ) {
baseUrl += '/' + options.longitude + '/' + options.latitude + '/' + options.radius
}
return this._clientRequest({
url: baseUrl,
extendedOptions: [
'includeNewFields'
],
}, function( error, data ) {
if( error != null )
return callback.call( self, error )
var airports = [].concat( data.airports || data.airport || [] )
.map( function( airport ) {
airport.tzOffset = airport.utcOffsetHours
airport.tzRegion = airport.timeZoneRegionName
airport.elevation = airport.elevationFeet * 0.305
airport.utcOffsetHours = undefined
delete airport.utcOffsetHours
airport.timeZoneRegionName = undefined
delete airport.timeZoneRegionName
return airport
})
callback.call( self, error, airports )
})
}
|
javascript
|
{
"resource": ""
}
|
|
q8196
|
train
|
function( options, callback ) {
debug( 'lookup' )
var now = Date.now()
var target = options.date.getTime()
// NOTE: `.status()` is only available within a window of -7 to +3 days
var timeMin = now - ( 8 * 24 ) * 60 * 60 * 1000
var timeMax = now + ( 3 * 24 ) * 60 * 60 * 1000
var method = target < timeMin || target > timeMax ?
'schedule' : 'status'
debug( 'lookup:time:target ', target )
debug( 'lookup:time:window', timeMin, timeMax )
debug( 'lookup:type', method )
return this[ method ]( options, callback )
}
|
javascript
|
{
"resource": ""
}
|
|
q8197
|
train
|
function( options, callback ) {
debug( 'schedule', options )
var self = this
var protocol = options.protocol || 'rest'
var format = options.format || 'json'
var baseUrl = 'schedules/' + protocol + '/v1/' + format + '/flight'
var carrier = options.airlineCode
var flightNumber = options.flightNumber
var year = options.date.getFullYear()
var month = options.date.getMonth() + 1
var day = options.date.getDate()
var direction = /^dep/i.test( options.direction ) ?
'departing' : 'arriving'
var extensions = [
'includeDirects',
'includeCargo',
'useInlinedReferences'
]
if( Array.isArray( options.extendedOptions ) ) {
extensions = extensions.concat( options.extendedOptions )
}
return this._clientRequest({
url: baseUrl + '/' + carrier + '/' + flightNumber + '/' + direction + '/' + year + '/' + month + '/' + day,
extendedOptions: extensions,
}, function( error, data ) {
if( data != null ) {
data = FlightStats.formatSchedule( data )
if( options.airport && data.flights ) {
data.flights = FlightStats.filterByAirport( data.flights, options.airport, options.direction )
}
}
callback.call( self, error, data )
})
}
|
javascript
|
{
"resource": ""
}
|
|
q8198
|
train
|
function( options, callback ) {
options = Object.assign({ type: 'firstflightin', verb: '/arriving_before/' }, options )
return this.connections( options, callback )
}
|
javascript
|
{
"resource": ""
}
|
|
q8199
|
train
|
function( options, callback ) {
var self = this
var year = options.date.getFullYear()
var month = options.date.getMonth() + 1
var day = options.date.getDate()
var hour = options.date.getHours()
var minute = options.date.getMinutes()
var url = '/connections/rest/v2/json/' + options.type + '/' + options.departureAirport + '/to/' + options.arrivalAirport +
options.verb + year + '/' + month + '/' + day + '/' + hour + '/' + minute
var extensions = []
if( Array.isArray( options.extendedOptions ) ) {
extensions = extensions.concat( options.extendedOptions )
}
var query = {
numHours: options.numHours,
maxResults: options.maxResults,
maxConnections: options.maxConnections,
minimumConnectTime: options.minimumConnectTime,
payloadType: options.payloadType,
includeAirlines: options.includeAirlines,
excludeAirlines: options.excludeAirlines,
includeAirports: options.includeAirports,
excludeAirports: options.excludeAirports,
includeSurface: options.includeSurface,
includeCodeshares: options.includeCodeshares,
includeMultipleCarriers: options.includeMultipleCarriers,
}
Object.keys( query ).forEach( function( key ) {
query[key] = query[key] != null ?
query[key] : undefined
})
return this._clientRequest({
url: url,
qs: query,
extendedOptions: extensions,
}, function( error, data ) {
callback.call( self, error, data )
})
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.