_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q5000
|
RecordKey
|
train
|
function RecordKey(path, recordType, name) {
this.path = LedgerPath.parse(path);
|
javascript
|
{
"resource": ""
}
|
q5001
|
pending
|
train
|
function pending(options) {
options = options || {};
var store = options.store;
var autoRemove = (typeof options.autoRemove === 'undefined') ? true : options.autoRemove;
if (!store) throw new Error('pending middleware requires a store');
return function pending(stanza, next) {
if (!stanza.id || !(stanza.type == 'result' || stanza.type == 'error')) {
return next();
}
var key = stanza.from + ':' + stanza.id;
store.get(key, function(err, data) {
if (err) {
next(err);
} else
|
javascript
|
{
"resource": ""
}
|
q5002
|
train
|
function() {
var dest = gulp.dest('tmp/');
dest.on('end', function() {
grunt.log.ok('Created tmp/fn.js');
});
|
javascript
|
{
"resource": ""
}
|
|
q5003
|
CoapServerNode
|
train
|
function CoapServerNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
var node = this;
// Store local copies of the node configuration (as defined in the .html)
node.options = {};
node.options.name = n.name;
node.options.port = n.port;
node._inputNodes = []; // collection of "coap in" nodes that represent coap resources
// Setup node-coap server and start
node.server = new coap.createServer();
node.server.on('request', function(req, res) {
node.handleRequest(req, res);
res.on('error', function(err) {
|
javascript
|
{
"resource": ""
}
|
q5004
|
train
|
function (showSignal) {
return function (msg) {
var b = new Buffer(1);
b.writeUInt8(showSignal ? 1 : 0, 0);
msg.addOption(new Option(Message.Option.URI_PATH, new
|
javascript
|
{
"resource": ""
}
|
|
q5005
|
pause
|
train
|
function pause (stream) {
var events = []
var onData = createEventListener('data', events)
var onEnd = createEventListener('end', events)
// buffer data
stream.on('data', onData)
// buffer end
stream.on('end', onEnd)
return {
end: function end () {
stream.removeListener('data', onData)
stream.removeListener('end', onEnd)
},
|
javascript
|
{
"resource": ""
}
|
q5006
|
train
|
function (data) {
var that = this;
if (!data) {
if (this._socketTimeout) {
clearTimeout(this._socketTimeout); //just in case
}
//waiting on data.
//logger.log("server: waiting on hello");
this._socketTimeout = setTimeout(function () {
that.handshakeFail("get_hello timed out");
}, 30 * 1000);
return;
}
clearTimeout(this._socketTimeout);
var env = this.client.parseMessage(data);
var msg = (env && env.hello) ? env.hello : env;
if (!msg) {
this.handshakeFail("failed to parse hello");
return;
}
this.client.recvCounter = msg.getId();
//logger.log("server: got a good hello! Counter was: " + msg.getId());
try {
if (msg.getPayload) {
var payload = msg.getPayload();
if (payload.length > 0) {
var r = new buffers.BufferReader(payload);
this.client.spark_product_id = r.shiftUInt16();
this.client.product_firmware_version = r.shiftUInt16();
|
javascript
|
{
"resource": ""
}
|
|
q5007
|
train
|
function () {
//client will set the counter property on the message
//logger.log("server: send hello");
this.client.secureOut = this.secureOut;
this.client.sendCounter = CryptoLib.getRandomUINT16();
|
javascript
|
{
"resource": ""
}
|
|
q5008
|
train
|
function () {
var that = this;
this.socket.setNoDelay(true);
this.socket.setKeepAlive(true, 15 * 1000); //every 15 second(s)
this.socket.on('error', function (err) {
that.disconnect("socket error " + err);
});
|
javascript
|
{
"resource": ""
}
|
|
q5009
|
train
|
function (data) {
var msg = messages.unwrap(data);
if (!msg) {
logger.error("routeMessage got a NULL coap message ", { coreID: this.getHexCoreID() });
return;
}
this._lastMessageTime = new Date();
//should be adequate
var msgCode = msg.getCode();
if ((msgCode > Message.Code.EMPTY) && (msgCode <= Message.Code.DELETE)) {
//probably a request
msg._type = messages.getRequestType(msg);
}
if (!msg._type) {
msg._type = this.getResponseType(msg.getTokenString());
}
//console.log("core got message of type " + msg._type + " with token " + msg.getTokenString() + " " + messages.getRequestType(msg));
if (msg.isAcknowledgement()) {
if (!msg._type) {
//no type, can't route it.
msg._type = 'PingAck';
}
this.emit(('msg_' + msg._type).toLowerCase(), msg);
return;
}
var nextPeerCounter = ++this.recvCounter;
if (nextPeerCounter > 65535) {
//TODO: clean me up! (I need settings, and maybe belong elsewhere)
this.recvCounter = nextPeerCounter = 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q5010
|
train
|
function (name, uri, token, callback, once) {
var tokenHex = (token) ? utilities.toHexString(token) : null;
var beVerbose = settings.showVerboseCoreLogs;
//TODO: failWatch? What kind of timeout do we want here?
//adds a one time event
var that = this,
evtName = ('msg_' + name).toLowerCase(),
handler = function (msg) {
if (uri && (msg.getUriPath().indexOf(uri) != 0)) {
if (beVerbose) {
logger.log("uri filter did not match", uri, msg.getUriPath(), { coreID: that.getHexCoreID() });
}
return;
}
|
javascript
|
{
"resource": ""
}
|
|
q5011
|
train
|
function (name, type, callback) {
var that = this;
var performRequest = function () {
if (!that.HasSparkVariable(name)) {
callback(null, null, "Variable not found");
return;
}
var token = this.sendMessage("VariableRequest", { name: name });
var varTransformer = this.transformVariableGenerator(name, callback);
|
javascript
|
{
"resource": ""
}
|
|
q5012
|
train
|
function (showSignal, callback) {
var timer = setTimeout(function () { callback(false); }, 30 * 1000);
//TODO: that.stopListeningFor("RaiseYourHandReturn", listenHandler);
//TODO: var listenHandler = this.listenFor("RaiseYourHandReturn", ...
|
javascript
|
{
"resource": ""
}
|
|
q5013
|
train
|
function (name, args) {
var ready = when.defer();
var that = this;
when(this.ensureWeHaveIntrospectionData()).then(
function () {
var buf = that._transformArguments(name, args);
if (buf) {
ready.resolve(buf);
}
else {
|
javascript
|
{
"resource": ""
}
|
|
q5014
|
train
|
function (name, msg, callback) {
var varType = "int32"; //if the core doesn't specify, assume it's a "uint32"
//var fnState = (this.coreFnState) ? this.coreFnState.f : null;
//if (fnState && fnState[name] && fnState[name].returns) {
// varType = fnState[name].returns;
//}
var niceResult = null;
try {
if (msg && msg.getPayload) {
niceResult = messages.FromBinary(msg.getPayload(), varType);
}
}
catch (ex) {
|
javascript
|
{
"resource": ""
}
|
|
q5015
|
train
|
function (name, args) {
//logger.log('transform args', { coreID: this.getHexCoreID() });
if (!args) {
return null;
}
if (!this.hasFnState()) {
logger.error("_transformArguments called without any function state!", { coreID: this.getHexCoreID() });
return null;
}
//TODO: lowercase function keys on new state format
name = name.toLowerCase();
var fn = this.coreFnState[name];
if (!fn || !fn.args) {
//maybe it's the old protocol?
var f = this.coreFnState.f;
if (f && utilities.arrayContainsLower(f, name)) {
//logger.log("_transformArguments - using old format", { coreID: this.getHexCoreID() });
//current / simplified function format (one string arg, int return type)
fn = {
returns: "int",
args: [
|
javascript
|
{
"resource": ""
}
|
|
q5016
|
train
|
function () {
if (this.hasFnState()) {
return when.resolve();
}
//if we don't have a message pending, send one.
|
javascript
|
{
"resource": ""
}
|
|
q5017
|
train
|
function(msg) {
//got a description, is it any good?
var loaded = (this.loadFnState(msg.getPayload()));
if (this._describeDfd) {
if (loaded) {
this._describeDfd.resolve();
}
|
javascript
|
{
"resource": ""
}
|
|
q5018
|
train
|
function(msg) {
//moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch).
var
|
javascript
|
{
"resource": ""
}
|
|
q5019
|
train
|
function (isPublic, name, data, ttl, published_at, coreid) {
var rawFn = function (msg) {
try {
msg.setMaxAge(parseInt((ttl && (ttl >= 0)) ? ttl : 60));
if (published_at) {
msg.setTimestamp(moment(published_at).toDate());
}
}
catch (ex) {
logger.error("onCoreHeard - " + ex);
}
return msg;
};
var msgName = (isPublic) ? "PublicEvent" : "PrivateEvent";
|
javascript
|
{
"resource": ""
}
|
|
q5020
|
train
|
function() {
if (this._chunkReceivedHandler) {
this.client.removeListener("ChunkReceived", this._chunkReceivedHandler);
}
this._chunkReceivedHandler = null;
// logger.log("HERE -
|
javascript
|
{
"resource": ""
}
|
|
q5021
|
train
|
function (name, seconds, callback) {
if (!this._timers) {
this._timers = {};
}
if (!seconds) {
clearTimeout(this._timers[name]);
delete this._timers[name];
}
else {
this._timers[name] = setTimeout(function () {
|
javascript
|
{
"resource": ""
}
|
|
q5022
|
train
|
function (fn, scope) {
return function () {
try {
return fn.apply(scope, arguments);
}
catch (ex) {
|
javascript
|
{
"resource": ""
}
|
|
q5023
|
train
|
function (left, right) {
if (!left && !right) {
return true;
}
var matches = true;
for (var prop in right) {
if (!right.hasOwnProperty(prop)) {
continue;
|
javascript
|
{
"resource": ""
}
|
|
q5024
|
train
|
function (dir, search, excludedDirs) {
excludedDirs = excludedDirs || [];
var result = [];
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
var fullpath = path.join(dir, files[i]);
var stat = fs.statSync(fullpath);
if (stat.isDirectory() && (!excludedDirs.contains(fullpath))) {
|
javascript
|
{
"resource": ""
}
|
|
q5025
|
train
|
function (arr, handler) {
var tmp = when.defer();
var index = -1;
var results = [];
var doNext = function () {
try {
index++;
if (index > arr.length) {
tmp.resolve(results);
}
var file = arr[index];
var promise = handler(file);
if (promise) {
when(promise).then(function (result) {
results.push(result);
process.nextTick(doNext);
}, function () {
process.nextTick(doNext);
});
// when(promise).ensure(function () {
//
|
javascript
|
{
"resource": ""
}
|
|
q5026
|
train
|
function(a, b) {
var keys = Object.keys(b)
, i = 0
, l = keys.length
, val;
for (; i < l; i++) {
val = b[keys[i]];
|
javascript
|
{
"resource": ""
}
|
|
q5027
|
train
|
function(a, b) {
var found = 0
, keys = Object.keys(b)
, i = 0
, l = keys.length
|
javascript
|
{
"resource": ""
}
|
|
q5028
|
getAttributes
|
train
|
function getAttributes(tag) {
let running = true;
const attributes = [];
const regexp = /(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/g;
while (running) {
const match = regexp.exec(tag);
if (match) {
attributes.push({
key: match[1],
|
javascript
|
{
"resource": ""
}
|
q5029
|
getPartial
|
train
|
function getPartial(attributes) {
const splitAttr = partition(attributes, (attribute) => attribute.key === 'src');
const sourcePath = splitAttr[0][0] && splitAttr[0][0].value;
let file;
if (sourcePath && fs.existsSync(options.basePath + sourcePath)) {
file = injectHTML(fs.readFileSync(options.basePath + sourcePath))
} else if (!sourcePath) {
gutil.log(`${pluginName}:`, new gutil.PluginError(pluginName, gutil.colors.red(`Some partial does not have 'src'
|
javascript
|
{
"resource": ""
}
|
q5030
|
replaceAttributes
|
train
|
function replaceAttributes(file, attributes) {
return (attributes || []).reduce((html, attrObj)
|
javascript
|
{
"resource": ""
}
|
q5031
|
getPagesConfig
|
train
|
function getPagesConfig(entry) {
const pages = {}
// 规范中定义每个单页文件结构
// index.html,main.js,App.vue
glob.sync(PAGE_PATH + '/*/main.js')
.forEach(filePath => {
const pageName = path.basename(path.dirname(filePath))
if (entry && entry !== pageName) return
|
javascript
|
{
"resource": ""
}
|
q5032
|
getHandler
|
train
|
function getHandler (method, getArgs, trans, domain = 'feathers') {
return function (req, res, next) {
res.setHeader('Allow', Object.values(allowedMethods).join(','));
let params = Object.assign({}, req.params || {});
delete params.service;
delete params.id;
delete params.subresources;
delete params[0];
req.feathers = { provider: 'rest' };
// Grab the service parameters. Use req.feathers and set the query to req.query
let query = req.query || {};
let headers = fp.dissoc('cookie', req.headers || {});
let cookies = req.cookies || {};
params = Object.assign({ query, headers }, params, req.feathers);
// Transfer the received file
if (req.file) {
params.file = req.file;
}
// method override
if ((method === 'update' || method === 'patch')
&& params.query.$method
&& params.query.$method.toLowerCase() === 'patch') {
method = 'patch'
delete params.query.$method
}
// Run the getArgs callback, if available, for additional parameters
const [service, ...args] = getArgs(req, res, next);
debug(`REST handler calling service \'${service}\'`, {
cmd: method,
path: req.path,
//args: args,
//params: params,
//feathers: req.feathers
});
// The service success callback which sets res.data or calls next() with the error
const callback =
|
javascript
|
{
"resource": ""
}
|
q5033
|
info
|
train
|
function info (cb) {
var data = {
name: pjson.name,
message: 'pong',
version: pjson.version,
node_env: process.env.NODE_ENV,
|
javascript
|
{
"resource": ""
}
|
q5034
|
parseCaseStatements
|
train
|
function parseCaseStatements (spec) {
return _(spec)
.remove(statement
|
javascript
|
{
"resource": ""
}
|
q5035
|
create
|
train
|
function create (spec) {
const accumulator = new Accumulator()
accumulator.value = spec.value
accumulator.context = spec.context
accumulator.reducer = {
spec: spec.context
|
javascript
|
{
"resource": ""
}
|
q5036
|
calculateCountOfReplacementChar
|
train
|
function calculateCountOfReplacementChar(string, replaceByChar = ' ') {
var characters = 0
string
.split('')
.forEach(char => {
var size = charSizes.get(char) || 1
characters += size
})
// All sizes were measured against
|
javascript
|
{
"resource": ""
}
|
q5037
|
sanitizeLines
|
train
|
function sanitizeLines(frame) {
// Sanitize newlines & replace tabs.
lines = stripAnsi(frame)
.replace(/\r/g, '')
.split('\n')
.map(l => l.replace(/\t/g, ' '))
// Remove left caret.
var leftCaretLine = lines.find(l => l.startsWith('>'))
if (leftCaretLine) {
lines[lines.indexOf(leftCaretLine)] = leftCaretLine.replace('>', ' ')
}
// Remove
|
javascript
|
{
"resource": ""
}
|
q5038
|
extractMessage
|
train
|
function extractMessage(error) {
var {message} = error
if (error.plugin === 'babel') {
// Hey Babel, you're not helping!
var filepath = error.id
var message = error.message
function stripFilePath() {
var index = message.indexOf(filepath)
console.log(index, filepath.length)
message = message.slice(0, index) + message.slice(filepath.length + 1)
|
javascript
|
{
"resource": ""
}
|
q5039
|
readSync
|
train
|
function readSync(description, options) {
var file = vfile(description)
file.contents =
|
javascript
|
{
"resource": ""
}
|
q5040
|
writeSync
|
train
|
function writeSync(description, options) {
var file = vfile(description)
|
javascript
|
{
"resource": ""
}
|
q5041
|
set
|
train
|
function set (target, key, value) {
const obj = {}
obj[key] = value
|
javascript
|
{
"resource": ""
}
|
q5042
|
train
|
function (certparams) {
var keys = forge.pki.rsa.generateKeyPair(2048);
this.publicKey = keys.publicKey;
this.privateKey = keys.privateKey;
|
javascript
|
{
"resource": ""
}
|
|
q5043
|
clear
|
train
|
function clear (store) {
const forDeletion = []
const now = Date.now()
for (const [key, entry] of store) {
// mark for deletion entries that have timed out
if (now - entry.created > entry.ttl) {
forDeletion.push(key)
}
}
const forDeletionLength = forDeletion.length
// if nothing to clean then exit
if (forDeletionLength === 0)
|
javascript
|
{
"resource": ""
}
|
q5044
|
exists
|
train
|
function exists (store, key) {
const entry = store.get(key)
// checks entry exists and it has not timed-out
|
javascript
|
{
"resource": ""
}
|
q5045
|
assignParamsHelper
|
train
|
function assignParamsHelper (accumulator, entity) {
if (accumulator.entityOverrides[entity.entityType]) {
return merge(
{},
|
javascript
|
{
"resource": ""
}
|
q5046
|
get
|
train
|
function get (manager, errorInfoCb, id) {
const value = manager.store.get(id)
if (_.isUndefined(value)) {
|
javascript
|
{
"resource": ""
}
|
q5047
|
isRevalidatingCacheKey
|
train
|
function isRevalidatingCacheKey (ctx, currentEntryKey) {
const revalidatingCache = ctx.locals.revalidatingCache
|
javascript
|
{
"resource": ""
}
|
q5048
|
resolveStaleWhileRevalidateEntry
|
train
|
function resolveStaleWhileRevalidateEntry (service, entryKey, cache, ctx) {
// NOTE: pulling through module.exports allows us to test if they were called
const {
resolveStaleWhileRevalidate,
isRevalidatingCacheKey,
shouldTriggerRevalidate,
revalidateEntry
} = module.exports
// IMPORTANT: we only want to bypass an entity that is being revalidated and
// that matches the same cache entry key, otherwise all child entities will
// be needlesly resolved
if (isRevalidatingCacheKey(ctx, entryKey)) {
// bypass the rest forces entity to get resolved
|
javascript
|
{
"resource": ""
}
|
q5049
|
train
|
function(a){
// Copy prototype properties.
for(var b in a.prototype){var c=b.match(/^(.*?[A-Z]{2,})(.*)$/),d=j(b);null!==c&&(d=c[1]+j(c[2])),d!==b&&(
// Add static methods as aliases.
d in a||(a[d]=function(b){return
|
javascript
|
{
"resource": ""
}
|
|
q5050
|
setSWRStaleEntry
|
train
|
function setSWRStaleEntry (service, key, value, ttl) {
|
javascript
|
{
"resource": ""
}
|
q5051
|
_getLocalPositionFromWorldPosition
|
train
|
function _getLocalPositionFromWorldPosition(transform) {
if (transform.parent === undefined)
return transform.position;
else
|
javascript
|
{
"resource": ""
}
|
q5052
|
_getWorldPositionFromLocalPosition
|
train
|
function _getWorldPositionFromLocalPosition(transform) {
if (transform.parent === undefined)
return transform.localPosition;
else
|
javascript
|
{
"resource": ""
}
|
q5053
|
_getLocalRotationFromWorldRotation
|
train
|
function _getLocalRotationFromWorldRotation(transform) {
if(transform.parent === undefined)
|
javascript
|
{
"resource": ""
}
|
q5054
|
_getWorldRotationFromLocalRotation
|
train
|
function _getWorldRotationFromLocalRotation(transform) {
if(transform.parent === undefined)
return transform.localRotation;
|
javascript
|
{
"resource": ""
}
|
q5055
|
_adjustChildren
|
train
|
function _adjustChildren(children) {
children.forEach(function (child) {
child.rotation = _getWorldRotationFromLocalRotation(child);
|
javascript
|
{
"resource": ""
}
|
q5056
|
_getLocalToWorldMatrix
|
train
|
function _getLocalToWorldMatrix(transform) {
return function() {
|
javascript
|
{
"resource": ""
}
|
q5057
|
_getWorldtoLocalMatrix
|
train
|
function _getWorldtoLocalMatrix(transform) {
return function() {
|
javascript
|
{
"resource": ""
}
|
q5058
|
_getRoot
|
train
|
function _getRoot(transform) {
return function() {
var parent = transform.parent;
return parent
|
javascript
|
{
"resource": ""
}
|
q5059
|
disposeInactiveEntries
|
train
|
function disposeInactiveEntries(
devMiddleware,
entries,
lastAccessPages,
maxInactiveAge
) {
const disposingPages = [];
Object.keys(entries).forEach(page => {
const { lastActiveTime, status } = entries[page];
// This means this entry is currently building or just added
// We don't need to dispose those entries.
if (status !== BUILT) return;
// We should not build the last accessed page even we didn't get any pings
// Sometimes, it's possible our XHR ping to wait before completing other requests.
// In that case,
|
javascript
|
{
"resource": ""
}
|
q5060
|
resolveOptions
|
train
|
function resolveOptions (accumulator, resolveReducer) {
const url = resolveUrl(accumulator)
const specOptions = accumulator.reducer.spec.options
return resolveReducer(accumulator, specOptions).then(acc => {
|
javascript
|
{
"resource": ""
}
|
q5061
|
train
|
function (p1x, p1y, p2x, p2y) {
return
|
javascript
|
{
"resource": ""
}
|
|
q5062
|
bootstrapAPI
|
train
|
function bootstrapAPI (cache) {
cache.set = set.bind(null, cache)
|
javascript
|
{
"resource": ""
}
|
q5063
|
_getRows
|
train
|
function _getRows(matrix) {
var rows = [];
for (var i=0; i<matrix.size.rows; i++) {
rows.push([]);
|
javascript
|
{
"resource": ""
}
|
q5064
|
_getColumns
|
train
|
function _getColumns(matrix) {
var cols = [];
for (var i=0; i<matrix.size.columns; i++) {
|
javascript
|
{
"resource": ""
}
|
q5065
|
_sizesMatch
|
train
|
function _sizesMatch(matrix1, matrix2) {
return matrix1.size.rows
|
javascript
|
{
"resource": ""
}
|
q5066
|
_fromVector
|
train
|
function _fromVector(vector) {
return new _Vector4(vector.values[0],
|
javascript
|
{
"resource": ""
}
|
q5067
|
_normalizedCoordinates
|
train
|
function _normalizedCoordinates(x, y, z, w) {
var magnitude = Math.sqrt(x * x + y * y + z * z + w * w);
if (magnitude === 0)
return this;
return {
|
javascript
|
{
"resource": ""
}
|
q5068
|
_fromAngleAxis
|
train
|
function _fromAngleAxis(axis, angle) {
var s = Math.sin(angle/2);
var c = Math.cos(angle/2);
|
javascript
|
{
"resource": ""
}
|
q5069
|
_getAngleAxis
|
train
|
function _getAngleAxis(quaternion) {
return function() {
var sqrt = Math.sqrt(1 - quaternion.w * quaternion.w);
return {
axis: new Vector3(quaternion.x / sqrt, quaternion.y
|
javascript
|
{
"resource": ""
}
|
q5070
|
normalizeInput
|
train
|
function normalizeInput (source) {
let result = ReducerList.parse(source)
if (result.length ===
|
javascript
|
{
"resource": ""
}
|
q5071
|
resolveReducer
|
train
|
function resolveReducer (manager, accumulator, reducer) {
// this conditional is here because BaseEntity#resolve
// does not check that lifecycle methods are defined
// before trying to resolve them
if (!reducer) {
return Promise.resolve(accumulator)
}
const isTracing = accumulator.trace
const acc = isTracing
? trace.augmentAccumulatorTrace(accumulator, reducer)
: accumulator
const traceNode = acc.traceNode
const resolve = getResolveFunction(reducer)
// NOTE: recursive call
let result = resolve(manager, resolveReducer, acc,
|
javascript
|
{
"resource": ""
}
|
q5072
|
_magnitudeOf
|
train
|
function _magnitudeOf(values) {
var result = 0;
for (var i = 0; i < values.length; i++)
|
javascript
|
{
"resource": ""
}
|
q5073
|
augmentAccumulatorTrace
|
train
|
function augmentAccumulatorTrace (accumulator, reducer) {
const acc = module.exports.createTracedAccumulator(accumulator,
|
javascript
|
{
"resource": ""
}
|
q5074
|
read
|
train
|
function read(description, options, callback) {
var file = vfile(description)
if (!callback && typeof options === 'function') {
callback = options
options = null
}
if (!callback) {
return new Promise(executor)
}
executor(resolve, callback)
function resolve(result) {
callback(null, result)
}
function executor(resolve, reject) {
var fp
try {
|
javascript
|
{
"resource": ""
}
|
q5075
|
write
|
train
|
function write(description, options, callback) {
var file = vfile(description)
// Weird, right? Otherwise `fs` doesn’t accept it.
if (!callback && typeof options === 'function') {
callback = options
options = undefined
}
if (!callback) {
return new Promise(executor)
}
executor(resolve, callback)
function resolve(result) {
callback(null, result)
}
function executor(resolve, reject) {
var fp
|
javascript
|
{
"resource": ""
}
|
q5076
|
warnLooseParamsCacheDeprecation
|
train
|
function warnLooseParamsCacheDeprecation (params) {
if (params.ttl || params.cacheKey
|
javascript
|
{
"resource": ""
}
|
q5077
|
_shutdownNextServices
|
train
|
async function _shutdownNextServices(reversedServiceSequence) {
if (0 === reversedServiceSequence.length) {
return;
}
await Promise.all(
reversedServiceSequence.pop().map(async serviceName => {
const singletonServiceDescriptor = await _this._pickupSingletonServiceDescriptorPromise(
serviceName,
);
const serviceDescriptor =
singletonServiceDescriptor ||
(await siloContext.servicesDescriptors.get(serviceName));
let serviceShutdownPromise =
_this._singletonsServicesShutdownsPromises.get(serviceName) ||
siloContext.servicesShutdownsPromises.get(serviceName);
if (serviceShutdownPromise) {
debug('Reusing a service shutdown promise:', serviceName);
return serviceShutdownPromise;
}
if (
reversedServiceSequence.some(servicesDeclarations =>
servicesDeclarations.includes(serviceName),
)
) {
debug('Delaying service shutdown:', serviceName);
return Promise.resolve();
}
if (singletonServiceDescriptor) {
const handleSet = _this._singletonsServicesHandles.get(
serviceName,
);
handleSet.delete(siloContext.name);
if (handleSet.size) {
debug('Singleton is used elsewhere:', serviceName, handleSet);
return Promise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
q5078
|
List
|
train
|
function List(options) {
if (!(this instanceof List)) {
return new List(options);
}
Base.call(this);
this.is('list');
this.define('isCollection', true);
|
javascript
|
{
"resource": ""
}
|
q5079
|
decorate
|
train
|
function decorate(list, method, prop) {
utils.define(list.items, method, function() {
var res =
|
javascript
|
{
"resource": ""
}
|
q5080
|
handleLayout
|
train
|
function handleLayout(obj, stats, depth) {
var layoutName = obj.layout.basename;
debug('applied layout (#%d) "%s", to file "%s"', depth, layoutName, file.path);
file.currentLayout = obj.layout;
|
javascript
|
{
"resource": ""
}
|
q5081
|
buildStack
|
train
|
function buildStack(app, name, view) {
var layoutExists = false;
var registered = 0;
var layouts = {};
// get all collections with `viewType` layout
var collections = app.viewTypes.layout;
var len = collections.length;
var idx = -1;
while (++idx < len) {
var collection = app[collections[idx]];
// detect if at least one of the collections has
// our starting layout
if (!layoutExists && collection.getView(name)) {
layoutExists = true;
}
// add the collection views to the layouts object
for (var key in collection.views) {
|
javascript
|
{
"resource": ""
}
|
q5082
|
Collection
|
train
|
function Collection(options) {
if (!(this instanceof Collection)) {
return new Collection(options);
}
|
javascript
|
{
"resource": ""
}
|
q5083
|
Templates
|
train
|
function Templates(options) {
if (!(this instanceof Templates)) {
return new Templates(options);
}
Base.call(this,
|
javascript
|
{
"resource": ""
}
|
q5084
|
setHelperOptions
|
train
|
function setHelperOptions(context, key) {
var optsHelper = context.options.helper || {};
if (optsHelper.hasOwnProperty(key)) {
|
javascript
|
{
"resource": ""
}
|
q5085
|
Context
|
train
|
function Context(app, view, context, helpers) {
this.helper = {};
this.helper.options = createHelperOptions(app, view, helpers);
this.context = context;
utils.define(this.context, 'view', view);
this.options = utils.merge({}, app.options, view.options, this.helper.options);
// make `this.options.handled` non-enumberable
utils.define(this.options, 'handled', this.options.handled);
|
javascript
|
{
"resource": ""
}
|
q5086
|
decorate
|
train
|
function decorate(obj) {
utils.define(obj, 'merge', function() {
var args = [].concat.apply([], [].slice.call(arguments));
var len = args.length;
var idx = -1;
while (++idx < len) {
var val = args[idx];
if (!utils.isObject(val)) continue;
if (val.hasOwnProperty('hash')) {
// shallow clone and delete the `data` object
val = utils.merge({}, val, val.hash);
delete val.data;
}
utils.merge(obj, val);
}
// ensure methods aren't overwritten
|
javascript
|
{
"resource": ""
}
|
q5087
|
mergePartials
|
train
|
function mergePartials(options) {
var opts = utils.merge({}, this.options, options);
var names = opts.mergeTypes || this.viewTypes.partial;
var partials = {};
var self = this;
names.forEach(function(name) {
var collection = self.views[name];
for (var key in collection) {
var view = collection[key];
// handle `onMerge` middleware
self.handleOnce('onMerge', view, function(err, res) {
if (err) throw err;
view = res;
});
if (view.options.nomerge)
|
javascript
|
{
"resource": ""
}
|
q5088
|
FixEncryptLength
|
train
|
function FixEncryptLength(text) {
var len = text.length;
var stdLens = [256, 512, 1024, 2048, 4096];
var stdLen, i, j;
for (i = 0; i < stdLens.length; i++) {
stdLen = stdLens[i];
if (len === stdLen) {
return text;
} else if (len < stdLen) {
var
|
javascript
|
{
"resource": ""
}
|
q5089
|
Group
|
train
|
function Group(config) {
if (!(this instanceof Group)) {
return new Group(config);
}
Base.call(this, config);
|
javascript
|
{
"resource": ""
}
|
q5090
|
handleErrors
|
train
|
function handleErrors(group, val) {
if (utils.isObject(val)) {
var List = group.List;
var keys = Object.keys(List.prototype);
keys.forEach(function(key) {
if (typeof val[key] !== 'undefined') return;
|
javascript
|
{
"resource": ""
}
|
q5091
|
objectFactory
|
train
|
function objectFactory(data) {
// if we are given an object Object, no-op and return it now.
if (_.isPlainObject(data)) {
return data;
}
// If we are given a byte Buffer, parse it as utf-8
if (data instanceof Buffer) {
data = data.toString('utf-8');
}
// If we now have a string, then assume it is a JSON string.
|
javascript
|
{
"resource": ""
}
|
q5092
|
createKafkaConsumerAsync
|
train
|
function createKafkaConsumerAsync(kafkaConfig) {
let topicConfig = {};
if ('default_topic_config' in kafkaConfig) {
topicConfig = kafkaConfig.default_topic_config;
|
javascript
|
{
"resource": ""
}
|
q5093
|
getAvailableTopics
|
train
|
function getAvailableTopics(topicsInfo, allowedTopics) {
const existentTopics = topicsInfo.map(
e => e.name
)
.filter(t => t !== '__consumer_offsets');
if (allowedTopics) {
|
javascript
|
{
"resource": ""
}
|
q5094
|
assignmentsForTimesAsync
|
train
|
function assignmentsForTimesAsync(kafkaConsumer, assignments) {
const assignmentsWithTimestamps = assignments.filter(a => 'timestamp' in a && !('offset' in a)).map((a) => {
return {topic: a.topic, partition: a.partition, offset: a.timestamp };
});
// If there were no timestamps to resolve, just return assignments as is.
if (assignmentsWithTimestamps.length == 0) {
return new P((resolve, reject) => resolve(assignments));
}
// Else resolve all timestamp assignments to offsets.
else {
// Get offsets for the timestamp based assignments.
// If no offset was found for any timestamp, this will return -1, which
// we can use for offset: -1 as end of partition.
return kafkaConsumer.offsetsForTimesAsync(assignmentsWithTimestamps)
|
javascript
|
{
"resource": ""
}
|
q5095
|
deserializeKafkaMessage
|
train
|
function deserializeKafkaMessage(kafkaMessage) {
kafkaMessage.message = objectFactory(kafkaMessage.value);
kafkaMessage.message._kafka = {
topic:
|
javascript
|
{
"resource": ""
}
|
q5096
|
findView
|
train
|
function findView(app, name) {
var keys = app.viewTypes.renderable;
var len = keys.length;
var i = -1;
var res = null;
while (++i
|
javascript
|
{
"resource": ""
}
|
q5097
|
getView
|
train
|
function getView(app, view) {
if (typeof view !== 'string') {
return view;
}
if (app.isCollection) {
view = app.getView(view);
} else if
|
javascript
|
{
"resource": ""
}
|
q5098
|
Generator
|
train
|
function Generator (fn, opts) {
if (fn instanceof Function) {
if (typeof opts === 'number') {
opts = {duration: opts};
}
else {
opts = opts || {};
}
opts.generate = fn;
}
else {
opts = fn || {};
}
//sort out arguments
opts = extend({
//total duration of a stream
duration: Infinity,
//time repeat period, in seconds, or 1/frequency
period: Infinity,
//inferred from period
//frequency: 0,
/**
* Generate sample value for a time.
* Returns [L, R, ...] or a number for each channel
*
* @param {number} time current time
*/
generate: Math.random
}, pcm.defaults, opts);
//align frequency/period
if (opts.frequency != null) {
opts.period = 1 / opts.frequency;
} else {
opts.frequency = 1 / opts.period;
}
let time = 0, count = 0;
return generate;
//return sync source/map
function generate (buffer) {
if (!buffer) buffer = util.create(opts.samplesPerFrame, opts.channels, opts.sampleRate);
//get audio buffer channels data in array
var data = util.data(buffer);
//enough?
if (time + buffer.length / opts.sampleRate > opts.duration) return null;
|
javascript
|
{
"resource": ""
}
|
q5099
|
deserializeQueryParam
|
train
|
function deserializeQueryParam(param) {
if (!!param && (typeof param === 'object'))
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.