_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q5500
|
formatIf
|
train
|
function formatIf (bool, format, arr, ref) {
if (bool) {
arr.unshift(format)
return
|
javascript
|
{
"resource": ""
}
|
q5501
|
prependUntilLength
|
train
|
function prependUntilLength (str, len, char) {
if (str.length >= len)
return str
else
return
|
javascript
|
{
"resource": ""
}
|
q5502
|
defined
|
train
|
function defined () {
for (var i=0; i<arguments.length; i++)
if (typeof arguments[i] !==
|
javascript
|
{
"resource": ""
}
|
q5503
|
Remote
|
train
|
function Remote(connection) {
this.timeout = 5000;
this._connection = connection;
this._handlers = {};
this._requestID = 1;
var self = this;
this._connection.addListener('response', function(res) {
if (res.id === null || res.id === undefined) { return; }
|
javascript
|
{
"resource": ""
}
|
q5504
|
validate
|
train
|
function validate(args, required) {
var result = {
error: false,
message: 'No errors'
}
// ensure required properties were passed in the arguments hash
if (required) {
var keys = _.keys(args);
required.forEach(function(field) {
if(!_.contains(keys, field)) {
|
javascript
|
{
"resource": ""
}
|
q5505
|
makeLogLineProto
|
train
|
function makeLogLineProto(message, time, level) {
var userAppLogLine = new apphosting.UserAppLogLine();
userAppLogLine.setTimestampUsec((time * 1000).toString());
|
javascript
|
{
"resource": ""
}
|
q5506
|
makeMemcacheSetProto
|
train
|
function makeMemcacheSetProto(key, value) {
var memcacheSetRequest = new apphosting.MemcacheSetRequest();
var item = new apphosting.MemcacheSetRequest.Item();
|
javascript
|
{
"resource": ""
}
|
q5507
|
makeTaskqueueAddProto
|
train
|
function makeTaskqueueAddProto(taskOptions) {
var taskqueueAddRequest = new apphosting.TaskQueueAddRequest();
taskqueueAddRequest.setUrl(taskOptions.url);
taskqueueAddRequest.setQueueName(goog.isDefAndNotNull(taskOptions.queueName) ?
taskOptions.queueName : 'default');
taskqueueAddRequest.setTaskName(goog.isDefAndNotNull(taskOptions.taskName) ?
taskOptions.taskName : '');
taskqueueAddRequest.setEtaUsec(goog.isDefAndNotNull(taskOptions.etaUsec) ?
taskOptions.etaUsec : '0');
var method = 'post';
if (goog.isDefAndNotNull(taskOptions.method)) {
method = taskOptions.method;
}
taskqueueAddRequest.setMethod(methodToProtoMethod[method]);
if (goog.isDefAndNotNull(taskOptions.body))
|
javascript
|
{
"resource": ""
}
|
q5508
|
makeBackgroundRequest
|
train
|
function makeBackgroundRequest(req, appId, moduleName, moduleVersion, moduleInstance, appengine) {
var escapedAppId = appId.replace(/[:.]/g, '_');
var token = escapedAppId + '/' + moduleName + '.' + moduleVersion + '.' + moduleInstance;
var result = {
appengine: {
devappserver: req.appengine.devappserver,
appId: appId,
moduleName: moduleName,
moduleVersion: moduleVersion,
|
javascript
|
{
"resource": ""
}
|
q5509
|
makeModulesGetHostnameProto
|
train
|
function makeModulesGetHostnameProto(module, version, instance) {
var getHostnameRequest = new apphosting.GetHostnameRequest();
getHostnameRequest.setModule(module);
|
javascript
|
{
"resource": ""
}
|
q5510
|
servoLoop
|
train
|
function servoLoop() {
timer = setTimeout(servoLoop, 500);
pwm.setPulseLength(steeringChannel, pulseLengths[nextPulse]);
|
javascript
|
{
"resource": ""
}
|
q5511
|
numberArrayToString
|
train
|
function numberArrayToString(a) {
var s = '';
for (var i in a) {
|
javascript
|
{
"resource": ""
}
|
q5512
|
stringToUint8Array
|
train
|
function stringToUint8Array(s) {
var a = new Uint8Array(s.length);
for(var i = 0, j = s.length; i < j; ++i) {
|
javascript
|
{
"resource": ""
}
|
q5513
|
Server
|
train
|
function Server(clientListener) {
net.Server.call(this);
this._services = [];
if (clientListener) { this.addListener('client', clientListener); }
var self = this;
this.addListener('connection', function(socket) {
var connection = new Connection(socket);
connection.once('connect', function(remote) {
self.emit('client', connection, remote);
});
connection.on('error', function(err) {
self.emit('clientError', err, this);
});
|
javascript
|
{
"resource": ""
}
|
q5514
|
synthesizeUrl
|
train
|
function synthesizeUrl(serviceConfig, req, res) {
const parameters = _.map(serviceConfig.getParameters(req, res), (value, key) => {
return `${key}=${value}`;
}).join('&');
if (parameters) {
|
javascript
|
{
"resource": ""
}
|
q5515
|
parse
|
train
|
function parse(string) {
var buffer = newBufferFromSize(16);
var j = 0;
for (var i = 0; i < 16; i++) {
buffer[i] = hex2byte[string[j++] + string[j++]];
|
javascript
|
{
"resource": ""
}
|
q5516
|
uuidNamed
|
train
|
function uuidNamed(hashFunc, version, arg1, arg2) {
var options = arg1 || {};
var callback = typeof arg1 === "function" ? arg1 : arg2;
var namespace = options.namespace;
var name = options.name;
var hash = crypto.createHash(hashFunc);
if (typeof namespace === "string") {
if (!check(namespace)) {
return error(invalidNamespace, callback);
}
namespace = parse(namespace);
} else if (namespace instanceof UUID) {
namespace = namespace.toBuffer();
} else if (!(namespace instanceof Buffer) || namespace.length !== 16) {
return error(invalidNamespace, callback);
}
var nameIsNotAString = typeof name !== "string";
if (nameIsNotAString && !(name instanceof Buffer)) {
return error(invalidName, callback);
}
hash.update(namespace);
hash.update(options.name, nameIsNotAString ? "binary" : "utf8");
var buffer = hash.digest();
var result;
switch (options.encoding && options.encoding[0]) {
case "b":
case "B":
buffer[6] = (buffer[6] & 0x0f) | version;
buffer[8] = (buffer[8] & 0x3f) | 0x80;
result = buffer;
break;
case "o":
case "U":
|
javascript
|
{
"resource": ""
}
|
q5517
|
train
|
async function( req, res, next ) {
try {
var csrfToken = 'default'
if ( req.cookies && req.cookies[ 'pong-security' ] ) {
var token = req.cookies[ 'pong-security' ]
if ( gui.getCsrfTokenForUser ) {
csrfToken = await gui.getCsrfTokenForUser( token )
} else if ( gui.userTokens[ token ] && gui.userTokens[ token ].csrfToken )
|
javascript
|
{
"resource": ""
}
|
|
q5518
|
ensureAuthenticated
|
train
|
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
req.authClient = new googleapis.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET);
|
javascript
|
{
"resource": ""
}
|
q5519
|
hasEmberVersion
|
train
|
function hasEmberVersion(major, minor) {
const numbers = VERSION.split('-')[0].split('.');
const actualMajor = parseInt(numbers[0], 10);
const actualMinor = parseInt(numbers[1],
|
javascript
|
{
"resource": ""
}
|
q5520
|
chain_requests
|
train
|
function chain_requests(ml, url) {
return (batches) => {
let promise = new Promise((resolve, reject) => resolve(new MonkeyLearnResponse()));
// attach requests for all the batches sequentially to the original promise and return _that_
return batches.reduce((promise, batch) =>
promise.then((response) =>
request(ml, {
url: url,
method: 'POST',
body: batch,
parse_response: false
})
.then(raw_response => {
response._add_raw_response(raw_response);
return response;
})
.catch(error => {
if (error.hasOwnProperty('response')) {
|
javascript
|
{
"resource": ""
}
|
q5521
|
generator
|
train
|
function generator(n) {
if (!n) return Date.now().toString(36).toUpperCase();
|
javascript
|
{
"resource": ""
}
|
q5522
|
Pagelet
|
train
|
function Pagelet(options) {
if (!this) return new Pagelet(options);
this.fuse();
options = options || {};
//
// Use the temper instance on Pipe if available.
//
if (options.bigpipe && options.bigpipe._temper) {
options.temper = options.bigpipe._temper;
}
this.writable('_enabled', []); // Contains all enabled pagelets.
this.writable('_disabled', []); // Contains all disable pagelets.
this.writable('_active', null); // Are we active.
this.writable('_req', options.req); // Incoming HTTP request.
this.writable('_res', options.res); // Incoming HTTP response.
this.writable('_params', options.params); // Params extracted from the route.
this.writable('_temper', options.temper);
|
javascript
|
{
"resource": ""
}
|
q5523
|
fragment
|
train
|
function fragment(content) {
var active = pagelet.active;
if (!active) content = '';
if (mode === 'sync') return fn.call(context, undefined, content);
data.id = data.id || pagelet.id; // Pagelet id.
data.path = data.path || pagelet.path; // Reference to the path.
data.mode = data.mode || pagelet.mode; // Pagelet render mode.
data.remove = active ? false : pagelet.remove; // Remove from DOM.
data.parent = pagelet._parent;
|
javascript
|
{
"resource": ""
}
|
q5524
|
optimizer
|
train
|
function optimizer(Pagelet, next) {
var prototype = Pagelet.prototype
, method = prototype.method
, status = prototype.status
, router = prototype.path
, name = prototype.name
, view = prototype.view
, log = debug('pagelet:'+ name);
//
// Generate a unique ID used for real time connection lookups.
//
prototype.id = options.id || [0, 1, 1, 1].map(generator).join('-');
//
// Parse the methods to an array of accepted HTTP methods. We'll only accept
// these requests and should deny every other possible method.
//
log('Optimizing pagelet');
if (!Array.isArray(method)) method = method.split(/[\s\,]+?/);
Pagelet.method = method.filter(Boolean).map(function transformation(method) {
return method.toUpperCase();
});
//
// Add the actual HTTP route and available HTTP methods.
//
if (router) {
log('Instantiating router for path %s', router);
Pagelet.router = new Route(router);
}
//
// Prefetch the template if a view is available. The view property is
// mandatory for all pagelets except the bootstrap Pagelet or if the
// Pagelet is just doing a redirect. We can resolve this edge case by
// checking if statusCode is in the 300~ range.
//
if (!view && name !== 'bootstrap' && !(status >= 300 && status < 400)) return next(
new Error('The '+ name +' pagelet should have a .view property.')
);
//
// Resolve the view to ensure the path is correct and prefetch
// the template through Temper.
//
if (view) {
prototype.view = view = path.resolve(prototype.directory, view);
temper.prefetch(view, prototype.engine);
}
//
// Ensure we have a custom error pagelet when we fail to render this fragment.
//
|
javascript
|
{
"resource": ""
}
|
q5525
|
worldDebug
|
train
|
function worldDebug() {
Crafty.e( RenderingMode + ', Color' )
.attr( {
x: engine.world.bounds.min.x,
y: engine.world.bounds.min.y,
w: engine.world.bounds.max.x - engine.world.bounds.min.x,
|
javascript
|
{
"resource": ""
}
|
q5526
|
train
|
function( options, part, isSleeping ) {
var entity = part.entity;
if ( options.showSleeping && isSleeping ) {
entity.alpha = 0.5;
}
if ( entity._x !== part.position.x - ( entity._w / 2 ) ) {
entity.matterMoved = true;
entity.x = part.position.x - ( entity._w / 2 );
}
if ( entity._y !== part.position.y - ( entity._h / 2 ) ) {
|
javascript
|
{
"resource": ""
}
|
|
q5527
|
train
|
function( entity, angle ) {
var angleFixed = Crafty.math.radToDeg( angle ).toFixed( 3 );
if ( angle === 0 || entity._rotation === angleFixed ) {
return;
}
|
javascript
|
{
"resource": ""
}
|
|
q5528
|
train
|
function( pointA, pointB ) {
var vector = _getVector( pointA, pointB );
|
javascript
|
{
"resource": ""
}
|
|
q5529
|
train
|
function( pointA, pointB ) {
return { x: pointB.x -
|
javascript
|
{
"resource": ""
}
|
|
q5530
|
Models
|
train
|
function Models(ml, base_url) {
this.ml = ml;
this.base_url = base_url;
if (includes(base_url, 'classifiers')) {
this.run_action = 'classify';
|
javascript
|
{
"resource": ""
}
|
q5531
|
ReconnectingWebSocket
|
train
|
function ReconnectingWebSocket (url, options) {
var me = this;
this.id = options && options.id || randomUUID();
this.url = url + '/?id=' + this.id;
this.socket = null;
this.opened = false;
this.closed = false;
this.options = {
reconnectTimeout: Infinity, // ms
reconnectInterval: 5000 // ms
//reconnectDecay: 2 // TODO: reconnect decay
};
// copy the options
if (options) {
if ('reconnectTimeout' in options) this.options.reconnectTimeout = options.reconnectTimeout;
if ('reconnectInterval' in options) this.options.reconnectInterval = options.reconnectInterval;
}
this.queue = [];
this.attempts = 0;
this.reconnectTimer = null;
function connect() {
me.socket = new WebSocket(me.url);
me.socket.onmessage = function (event) {
me.onmessage(event);
};
me.socket.onerror = function (error) {
if (me.socket.readyState === WebSocket.OPEN) {
me.onerror(error);
}
else {
reconnect();
}
};
me.socket.onopen = function (event) {
// reset the number of connection attempts
me.attempts = 0;
// emit events
if (!me.opened) {
me.onopen(event);
me.opened = true;
}
else {
|
javascript
|
{
"resource": ""
}
|
q5532
|
train
|
function(jwt) {
try {
var segments = jwt.split('.');
this.signature = segments.pop();
this.signatureBase = segments.join('.');
this.header = decodeSegment(segments.shift());
|
javascript
|
{
"resource": ""
}
|
|
q5533
|
gulpBower
|
train
|
function gulpBower(opts, cmdArguments) {
opts = parseOptions(opts);
log.info('Using cwd: ' + opts.cwd);
log.info('Using bower dir: ' + opts.directory);
cmdArguments = createCmdArguments(cmdArguments, opts);
var bowerCommand = getBowerCommand(cmd);
var stream = through.obj(function (file, enc, callback) {
this.push(file);
callback();
});
bowerCommand.apply(bower.commands, cmdArguments)
.on('log', function (result) {
log.info(['bower', colors.cyan(result.id), result.message].join(' '));
|
javascript
|
{
"resource": ""
}
|
q5534
|
parseOptions
|
train
|
function parseOptions(opts) {
opts = opts || {};
if (toString.call(opts) === '[object String]') {
opts = {
directory: opts
};
}
opts.cwd = opts.cwd || process.cwd();
log.verbosity = toString.call(opts.verbosity) === '[object Number]' ? opts.verbosity : DEFAULT_VERBOSITY;
delete (opts.verbosity);
cmd = opts.cmd || DEFAULT_CMD;
delete (opts.cmd);
// enable bower prompting but ignore the
|
javascript
|
{
"resource": ""
}
|
q5535
|
getDirectoryFromBowerRc
|
train
|
function getDirectoryFromBowerRc(cwd) {
var bowerrc = path.join(cwd, '.bowerrc');
if (!fs.existsSync(bowerrc)) {
return '';
|
javascript
|
{
"resource": ""
}
|
q5536
|
createCmdArguments
|
train
|
function createCmdArguments(cmdArguments, opts) {
if (toString.call(cmdArguments) !== '[object Array]') {
cmdArguments = [];
}
if (toString.call(cmdArguments[0]) !== '[object Array]') {
|
javascript
|
{
"resource": ""
}
|
q5537
|
getBowerCommand
|
train
|
function getBowerCommand(cmd) {
// bower has some commands that are provided in a nested object structure, e.g. `bower cache clean`.
var bowerCommand;
// clean up the command given, to avoid unnecessary errors
cmd = cmd.trim();
var nestedCommand = cmd.split(' ');
if (nestedCommand.length > 1) {
// To enable that kind of nested commands, we try to resolve those commands, before passing them to bower.
for (var commandPos = 0; commandPos < nestedCommand.length; commandPos++) {
if (bowerCommand) {
// when the root command is already there, walk into the depth.
bowerCommand = bowerCommand[nestedCommand[commandPos]];
} else {
// the first time we look for the "root" commands available in bower
bowerCommand = bower.commands[nestedCommand[commandPos]];
}
}
|
javascript
|
{
"resource": ""
}
|
q5538
|
writeStreamToFs
|
train
|
function writeStreamToFs(opts, stream) {
var baseDir = path.join(opts.cwd, opts.directory);
var walker = walk.walk(baseDir);
walker.on('errors', function (root, stats, next) {
stream.emit('error', new PluginError(PLUGIN_NAME, stats.error));
next();
});
walker.on('directory', function (root, stats, next) {
next();
});
walker.on('file', function (root, stats, next) {
var filePath = path.resolve(root, stats.name);
fs.readFile(filePath, function (error, data) {
if (error) {
stream.emit('error', new PluginError(PLUGIN_NAME, error));
|
javascript
|
{
"resource": ""
}
|
q5539
|
train
|
function(options, authorizationCode, idToken, accessToken) {
this.options = options;
this.authorizationCode = authorizationCode;
this.profile = {};
this.credentials = {
id_token: idToken,
access_token: accessToken
};
this.now = Date.now();
this.apiKey = options.apiKey;
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.redirectUri
|
javascript
|
{
"resource": ""
}
|
|
q5540
|
train
|
function(location) {
var found = false;
while(!found) {
if (exists(location + '/package.json')) {
found = location;
} else if (location !== '/') {
|
javascript
|
{
"resource": ""
}
|
|
q5541
|
train
|
function(name) {
// Walk up the module call tree until we find a module containing name in its peerOptionalDependencies
var currentModule = module;
var found = false;
while (currentModule) {
// Check currentModule has a package.json
location = currentModule.filename;
var location = find_package_json(location)
if (!location) {
currentModule = get_parent_module(currentModule);
continue;
}
// Read the package.json file
var object = JSON.parse(fs.readFileSync(f('%s/package.json', location)));
// Is the name defined by interal file references
var parts = name.split(/\//);
// Check whether this package.json contains peerOptionalDependencies containing the
|
javascript
|
{
"resource": ""
}
|
|
q5542
|
ReconnectingConnection
|
train
|
function ReconnectingConnection(id, connection) {
this.id = id;
this.connection = null;
this.closed = false;
|
javascript
|
{
"resource": ""
}
|
q5543
|
ReconnectingWebSocketServer
|
train
|
function ReconnectingWebSocketServer (options, callback) {
var me = this;
this.port = options && options.port || null;
this.server = new WebSocketServer({port: this.port}, callback);
this.connections = {};
this.server.on('connection', function (conn) {
var urlParts = url.parse(conn.upgradeReq.url, true);
var id = urlParts.query.id;
if (id) {
// create a connection with id
var rConn = me.connections[id];
if (rConn) {
// update existing connection
// TODO: test for conflicts, if the connection or rConn is still opened by another client with the same id
rConn.setConnection(conn);
}
else {
// create
|
javascript
|
{
"resource": ""
}
|
q5544
|
extract
|
train
|
function extract(str, options) {
const defaults = { tolerant: true, comment: true, tokens: true, range: true, loc: true };
const tokens = esprima.tokenize(str, Object.assign({}, defaults, options));
const comments = [];
for (let i = 0; i < tokens.length; i++) {
let n = i + 1;
const token = tokens[i];
let next = tokens[n];
if (isComment(token)) {
|
javascript
|
{
"resource": ""
}
|
q5545
|
train
|
function (count, fn) { // 55
var self = this; // 56
var timeout = self._timeout(count); // 57
if (self.retryTimer) // 58
clearTimeout(self.retryTimer);
|
javascript
|
{
"resource": ""
}
|
|
q5546
|
train
|
function (isSignaled, options) {
this.queue = [];
this.isSignaled
|
javascript
|
{
"resource": ""
}
|
|
q5547
|
onClientPostRequestHandler
|
train
|
function onClientPostRequestHandler (ctx, err) {
// extension error
if (err) {
let error = null;
if (err instanceof SuperError) {
error = err.rootCause || err.cause || err;
} else {
error = err;
}
const internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err);
ctx.log.error(internalError);
ctx.emit('clientResponseError', error);
ctx._execute(error);
return;
}
if (ctx._response.payload.error) {
debug('act:response.payload.error', ctx._response.payload.error);
|
javascript
|
{
"resource": ""
}
|
q5548
|
onClientTimeoutPostRequestHandler
|
train
|
function onClientTimeoutPostRequestHandler (ctx, err) {
if (err) {
let error = null;
if (err instanceof SuperError) {
error = err.rootCause || err.cause || err;
} else {
error = err;
}
let internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err);
ctx.log.error(internalError);
ctx._response.error = error;
ctx.emit('clientResponseError', error);
}
try {
ctx._execute(ctx._response.error);
} catch(err) {
let error = null;
if (err instanceof SuperError) {
error = err.rootCause || err.cause || err;
} else {
error = err;
|
javascript
|
{
"resource": ""
}
|
q5549
|
onPreRequestHandler
|
train
|
function onPreRequestHandler (ctx, err) {
let m = ctx._encoderPipeline.run(ctx._message, ctx);
// encoding issue
if (m.error) {
let error = new Errors.ParseError(Constants.PAYLOAD_PARSING_ERROR).causedBy(m.error);
ctx.log.error(error);
ctx.emit('clientResponseError', error);
ctx._execute(error);
return;
}
if (err) {
let error = null;
if (err instanceof SuperError) {
error = err.rootCause || err.cause || err;
} else {
error = err;
}
const internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err);
ctx.log.error(internalError);
ctx.emit('clientResponseError', error);
ctx._execute(error);
return;
}
ctx._request.payload = m.value;
ctx._request.error = m.error;
// use simple publish mechanism instead of request/reply
if (ctx._pattern.pubsub$ === true) {
if (ctx._actCallback) {
ctx.log.info(Constants.PUB_CALLBACK_REDUNDANT);
}
|
javascript
|
{
"resource": ""
}
|
q5550
|
onServerPreHandler
|
train
|
function onServerPreHandler (ctx, err, value) {
if (err) {
if (err instanceof SuperError) {
ctx._response.error = err.rootCause || err.cause || err;
} else {
ctx._response.error = err;
}
const internalError = new Errors.MostlyError(
Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err);
ctx.log.error(internalError);
return ctx.finish();
}
// reply value from extension
if (value) {
ctx._response.payload = value;
return ctx.finish();
}
try {
let action = ctx._actMeta.action.bind(ctx);
// execute add middlewares
ctx._actMeta.dispatch(ctx._request, ctx._response, (err) => {
// middleware error
if (err) {
if (err instanceof SuperError) {
ctx._response.error = err.rootCause || err.cause || err;
} else {
ctx._response.error = err;
}
let internalError = new Errors.MostlyError(
Constants.ADD_MIDDLEWARE_ERROR, ctx.errorDetails).causedBy(err);
ctx.log.error(internalError);
return ctx.finish();
}
// if request type is 'pubsub' we dont have to reply back
if (ctx._request.payload.request.type === Constants.REQUEST_TYPE_PUBSUB) {
action(ctx._request.payload.pattern);
|
javascript
|
{
"resource": ""
}
|
q5551
|
onServerPreRequestHandler
|
train
|
function onServerPreRequestHandler (ctx, err, value) {
if (err) {
if (err instanceof SuperError) {
ctx._response.error = err.rootCause || err.cause || err;
} else {
ctx._response.error = err;
}
return ctx.finish();
}
// reply value from extension
if (value) {
ctx._response.payload = value;
return ctx.finish();
}
// check if a handler is registered with this pattern
if (ctx._actMeta) {
ctx._extensions.onServerPreHandler.dispatch(ctx, (err, val) =>
|
javascript
|
{
"resource": ""
}
|
q5552
|
onServerPreResponseHandler
|
train
|
function onServerPreResponseHandler (ctx, err, value) {
// check if an error was already wrapped
if (ctx._response.error) {
ctx.emit('serverResponseError', ctx._response.error);
ctx.log.error(ctx._response.error);
} else if (err) { // check for an extension error
if (err instanceof SuperError) {
ctx._response.error = err.rootCause || err.cause || err;
} else {
ctx._response.error = err;
}
const internalError = new Errors.MostlyError(
Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err);
ctx.log.error(internalError);
ctx.emit('serverResponseError', ctx._response.error);
}
// reply value from extension
if (value) {
ctx._response.payload = value;
}
// create message payload
ctx._buildMessage();
// indicates that an error occurs and that the program should exit
if (ctx._shouldCrash) {
// only when we have an
|
javascript
|
{
"resource": ""
}
|
q5553
|
onClose
|
train
|
function onClose (ctx, err, val, cb) {
// no callback no queue processing
if (!_.isFunction(cb)) {
ctx._heavy.stop();
ctx._transport.close();
if (err) {
ctx.log.fatal(err);
ctx.emit('error', err);
}
return;
}
// unsubscribe all active subscriptions
ctx.removeAll();
// wait until the client has flush all messages to nats
ctx._transport.flush(() => {
ctx._heavy.stop();
// close NATS
ctx._transport.close();
|
javascript
|
{
"resource": ""
}
|
q5554
|
checkPlugin
|
train
|
function checkPlugin (fn, version) {
if (typeof fn !== 'function') {
throw new TypeError(`mostly-plugin expects a function, instead got a '${typeof fn}'`);
}
if (version) {
if (typeof version !== 'string') {
throw new TypeError(`mostly-plugin expects a version string as second parameter, instead got '${typeof version}'`);
}
|
javascript
|
{
"resource": ""
}
|
q5555
|
getControllerDir
|
train
|
function getControllerDir(isInstall) {
// Find the js-controller location
const possibilities = ["iobroker.js-controller", "ioBroker.js-controller"];
let controllerPath;
for (const pkg of possibilities) {
try {
const possiblePath = require.resolve(pkg);
if (fs.existsSync(possiblePath)) {
controllerPath = possiblePath;
break;
}
}
catch (_a) {
/* not found */
|
javascript
|
{
"resource": ""
}
|
q5556
|
train
|
function (cb) {
Model.findById(parentPk, { include: [{ all : true }]}).then(function(parentRecord) {
if (!parentRecord) return cb({status: 404});
if (!parentRecord[relation]) { return cb({status: 404}); }
|
javascript
|
{
"resource": ""
}
|
|
q5557
|
createChild
|
train
|
function createChild(customCb) {
ChildModel.create(child).then(function(newChildRecord){
if (req._sails.hooks.pubsub) {
if (req.isSocket) {
ChildModel.subscribe(req, newChildRecord);
ChildModel.introduce(newChildRecord);
}
ChildModel.publishCreate(newChildRecord, !req.options.mirror && req);
}
// in case we have to create a child and link it to parent(M-M through scenario)
// createChild function should return the instance to be linked
// in the
|
javascript
|
{
"resource": ""
}
|
q5558
|
train
|
function () {
if (_uniq(matchup, true).length < 2) return 1
|
javascript
|
{
"resource": ""
}
|
|
q5559
|
train
|
function () {
if (_uniq(matchup, true).length < 2) return 0
|
javascript
|
{
"resource": ""
}
|
|
q5560
|
isIrrelevant
|
train
|
function isIrrelevant(tile) {
return !tile
|| !tile.physics
|| !tile.physics.matterBody
|| !tile.physics.matterBody.body
|
javascript
|
{
"resource": ""
}
|
q5561
|
containsNormal
|
train
|
function containsNormal(normal, normals) {
let n;
for (n = 0; n < normals.length;
|
javascript
|
{
"resource": ""
}
|
q5562
|
buildEdgeVertex
|
train
|
function buildEdgeVertex(index, x, y, tileBody, isGhost) {
let vertex = {
x: x,
y: y,
index: index,
body: tileBody,
|
javascript
|
{
"resource": ""
}
|
q5563
|
buildEdge
|
train
|
function buildEdge(vertex1, vertex2, tileBody, vertex0, vertex3) {
vertex0 = vertex0 || null;
vertex3 = vertex3 || null;
let vertices = [];
// Build the vertices
vertices.push(
vertex0 ? buildEdgeVertex(0, vertex0.x, vertex0.y, tileBody, true) : null,
buildEdgeVertex(1, vertex1.x, vertex1.y, tileBody),
buildEdgeVertex(2, vertex2.x, vertex2.y, tileBody),
vertex3 ? buildEdgeVertex(3, vertex3.x, vertex3.y, tileBody, true) : null
);
// Build the edge
let edge = {
vertices: vertices,
|
javascript
|
{
"resource": ""
}
|
q5564
|
isAxisAligned
|
train
|
function isAxisAligned(vector) {
for (let d in Constants.Directions) {
let direction
|
javascript
|
{
"resource": ""
}
|
q5565
|
train
|
function (tilemapLayer, tiles) {
let i, layerData = tilemapLayer.layer;
// Pre-process the tiles
for (i in tiles) {
let tile = tiles[i];
tile.physics.slopes = tile.physics.slopes || {};
tile.physics.slopes = {
neighbours: {
up: GetTileAt(tile.x, tile.y - 1, true, layerData),
down: GetTileAt(tile.x, tile.y + 1, true, layerData),
left: GetTileAt(tile.x - 1, tile.y, true, layerData),
right: GetTileAt(tile.x + 1, tile.y, true, layerData),
topLeft: GetTileAt(tile.x - 1, tile.y - 1, true, layerData),
topRight: GetTileAt(tile.x + 1, tile.y - 1, true, layerData),
bottomLeft: GetTileAt(tile.x - 1, tile.y + 1, true, layerData),
bottomRight: GetTileAt(tile.x + 1, tile.y + 1, true, layerData),
},
edges: {
|
javascript
|
{
"resource": ""
}
|
|
q5566
|
train
|
function (firstEdge, secondEdge) {
if (firstEdge === Constants.SOLID && secondEdge === Constants.SOLID) {
|
javascript
|
{
"resource": ""
}
|
|
q5567
|
train
|
function (tiles) {
const maxDist = 5;
const directNeighbours = ['up', 'down', 'left', 'right'];
let t, tile, n, neighbour, i, j, tv, nv, tn, nn;
for (t = 0; t < tiles.length; t++) {
tile = tiles[t];
// Skip over irrelevant tiles
if (isIrrelevant(tile)) {
continue;
}
// Grab the tile's body and vertices to compare with its neighbours
let tileBody = tile.physics.matterBody.body;
let tileVertices = tileBody.vertices;
// Iterate over each direct neighbour
for (n in directNeighbours) {
neighbour = tile.physics.slopes.neighbours[directNeighbours[n]];
// Skip over irrelevant neighbouring tiles
if (isIrrelevant(neighbour)) {
continue;
}
|
javascript
|
{
"resource": ""
}
|
|
q5568
|
onClientPreRequestCircuitBreaker
|
train
|
function onClientPreRequestCircuitBreaker (ctx, next) {
if (ctx._config.circuitBreaker.enabled) {
// any pattern represent an own circuit breaker
const circuitBreaker = ctx._circuitBreakerMap.get(ctx.trace$.method);
if (!circuitBreaker) {
const cb = new CircuitBreaker(ctx._config.circuitBreaker);
ctx._circuitBreakerMap.set(ctx.trace$.method, cb);
} else {
if (!circuitBreaker.available()) {
// trigger half-open timer
|
javascript
|
{
"resource": ""
}
|
q5569
|
train
|
function (namespace) {
if (namespace) {
if (!this.namespaces[namespace]) {
return []
}
return _.keys(this.namespaces[namespace].services)
} else {
|
javascript
|
{
"resource": ""
}
|
|
q5570
|
train
|
function (service) {
let s
const ns = _.values(this.namespaces)
if (!ns || !ns.length) {
return s
}
for (let i = 0; i < ns.length; i++) {
const n = ns[i]
|
javascript
|
{
"resource": ""
}
|
|
q5571
|
hasKey
|
train
|
function hasKey(key) {
return data.meta[key] !== undefined
&& (self.lookup[key] ===
|
javascript
|
{
"resource": ""
}
|
q5572
|
render
|
train
|
function render(file, data, outputDir) {
if (!argv.unsafe && path.extname(file) === '.html')
return console.error(chalk.red(file + ': To use .html as source files, add --unsafe/-u flag'))
env.render(file, data, function(err, res) {
if (err) return console.error(chalk.red(err))
var outputFile = file.replace(/\.\w+$/, '') + '.html'
if (outputDir) {
outputFile =
|
javascript
|
{
"resource": ""
}
|
q5573
|
renderAll
|
train
|
function renderAll(files, data, outputDir) {
for (var i = 0; i < files.length; i++) {
|
javascript
|
{
"resource": ""
}
|
q5574
|
yarn
|
train
|
function yarn(cmds, args, cb) {
if (typeof args === 'function') {
return yarn(cmds, [], args);
}
args = arrayify(cmds).concat(arrayify(args));
spawn('yarn', args, {cwd: cwd, stdio: 'inherit'})
|
javascript
|
{
"resource": ""
}
|
q5575
|
deps
|
train
|
function deps(type, flags, names, cb) {
names = flatten([].slice.call(arguments, 2));
cb = names.pop();
if (type && names.length === 0) {
names = keys(type);
|
javascript
|
{
"resource": ""
}
|
q5576
|
train
|
function (options) {
this.queue = [];
this.ownerTokenId
|
javascript
|
{
"resource": ""
}
|
|
q5577
|
applyGroupBy
|
train
|
function applyGroupBy(images, options) {
return Promise.reduce(options.groupBy, function (images, group) {
return Promise.map(images, function (image) {
return Promise.resolve(group(image)).then(function (group) {
if (group) {
image.groups.push(group);
|
javascript
|
{
"resource": ""
}
|
q5578
|
setTokens
|
train
|
function setTokens(images, options, css) {
return new Promise(function (resolve) {
css.walkAtRules('lazysprite', function (atRule) {
// Get the directory of images from atRule value
var params = space(atRule.params);
var atRuleValue = getAtRuleValue(params);
var sliceDir = atRuleValue[0];
var sliceDirname = sliceDir.split(path.sep).pop();
var atRuleParent = atRule.parent;
var mediaAtRule2x = postcss.atRule({name: 'media', params: resolutions2x.join(', ')});
var mediaAtRule3x = postcss.atRule({name: 'media', params: resolutions3x.join(', ')});
// Tag flag
var has2x = false;
var has3x = false;
if (options.outputExtralCSS) {
var outputExtralCSSRule = postcss.rule({
selector: '.' + options.nameSpace + (atRuleValue[1] ? atRuleValue[1] : sliceDirname),
source: atRule.source
});
outputExtralCSSRule.append({prop: 'display', value: 'inline-block'});
outputExtralCSSRule.append({prop: 'overflow', value: 'hidden'});
outputExtralCSSRule.append({prop: 'font-size', value: '0'});
outputExtralCSSRule.append({prop: 'line-height', value: '0'});
atRule.before(outputExtralCSSRule);
}
// Foreach every image object
_.forEach(images, function (image) {
// Only work when equal to directory name
if (sliceDirname === image.dir) {
image.token = postcss.comment({
text: image.path,
raws: {
between: options.cloneRaws.between,
after: options.cloneRaws.after,
left: '@replace|',
right: ''
}
});
// Add
|
javascript
|
{
"resource": ""
}
|
q5579
|
saveSprites
|
train
|
function saveSprites(images, options, sprites) {
return new Promise(function (resolve, reject) {
if (!fs.existsSync(options.spritePath)) {
mkdirp.sync(options.spritePath);
}
var all = _
.chain(sprites)
.map(function (sprite) {
sprite.path = makeSpritePath(options, sprite.groups);
var deferred = Promise.pending();
// If this file is up to date
if (sprite.isFromCache) {
log(options.logLevel, 'lv3', ['Lazysprite:', colors.yellow(path.relative(process.cwd(), sprite.path)), 'unchanged.']);
deferred.resolve(sprite);
return deferred.promise;
}
// Save new file version
|
javascript
|
{
"resource": ""
}
|
q5580
|
mapSpritesProperties
|
train
|
function mapSpritesProperties(images, options, sprites) {
return new Promise(function (resolve) {
sprites = _.map(sprites, function (sprite) {
return _.map(sprite.coordinates, function (coordinates, imagePath) {
return _.merge(_.find(images, {path: imagePath}), {
|
javascript
|
{
"resource": ""
}
|
q5581
|
updateReferences
|
train
|
function updateReferences(images, options, sprites, css) {
return new Promise(function (resolve) {
css.walkComments(function (comment) {
var rule, image, backgroundImage, backgroundPosition, backgroundSize;
// Manipulate only token comments
if (isToken(comment)) {
// Match from the path with the tokens comments
image = _.find(images, {path: comment.text});
if (image) {
// 2x check even dimensions.
if (image.ratio === 2 && (image.coordinates.width % 2 !== 0 || image.coordinates.height % 2 !== 0)) {
throw log(options.logLevel, 'lv1', ['Lazysprite:', colors.red(path.relative(process.cwd(), image.path)), '`2x` image should have' +
' even dimensions.']);
}
// 3x check dimensions.
if (image.ratio === 3 && (image.coordinates.width % 3 !== 0 || image.coordinates.height % 3 !== 0)) {
throw log(options.logLevel, 'lv1', ['Lazysprite:', colors.red(path.relative(process.cwd(), image.path)), '`3x` image should have' +
|
javascript
|
{
"resource": ""
}
|
q5582
|
makeSpritePath
|
train
|
function makeSpritePath(options, groups) {
var base = options.spritePath;
var file;
// If is svg, do st
if (groups.indexOf('GROUP_SVG_FLAG') > -1) {
groups = _.filter(groups, function (item) {
return item !== 'GROUP_SVG_FLAG';
});
file = path.resolve(base,
|
javascript
|
{
"resource": ""
}
|
q5583
|
getBackgroundPosition
|
train
|
function getBackgroundPosition(image) {
var logicValue = image.isSVG ? 1 : -1;
var x = logicValue * (image.ratio > 1 ? image.coordinates.x / image.ratio : image.coordinates.x);
var y = logicValue * (image.ratio > 1
|
javascript
|
{
"resource": ""
}
|
q5584
|
getBackgroundPositionInPercent
|
train
|
function getBackgroundPositionInPercent(image) {
var x = 100 * (image.coordinates.x) / (image.properties.width - image.coordinates.width);
var y = 100 * (image.coordinates.y) / (image.properties.height
|
javascript
|
{
"resource": ""
}
|
q5585
|
getBackgroundSize
|
train
|
function getBackgroundSize(image) {
var x = image.properties.width / image.ratio;
var y = image.properties.height / image.ratio;
var template =
|
javascript
|
{
"resource": ""
}
|
q5586
|
getRetinaRatio
|
train
|
function getRetinaRatio(url) {
var matches = /[@_](\d)x\.[a-z]{3,4}$/gi.exec(url);
if (!matches) {
return 1;
|
javascript
|
{
"resource": ""
}
|
q5587
|
log
|
train
|
function log(logLevel, level, content) {
var output = true;
switch (logLevel) {
case 'slient':
if (level !== 'lv1') {
output = false;
|
javascript
|
{
"resource": ""
}
|
q5588
|
debug
|
train
|
function debug() {
var data = Array.prototype.slice.call(arguments);
|
javascript
|
{
"resource": ""
}
|
q5589
|
Gmsmith
|
train
|
function Gmsmith(options) {
options = options || {};
this.gm = _gm;
var useImageMagick = options.hasOwnProperty('imagemagick')
|
javascript
|
{
"resource": ""
}
|
q5590
|
setItem
|
train
|
function setItem(key, value) {
storage[key] = typeof value ===
|
javascript
|
{
"resource": ""
}
|
q5591
|
log
|
train
|
function log(text) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'success';
var debug$$1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!debug$$1) {
return;
|
javascript
|
{
"resource": ""
}
|
q5592
|
parse
|
train
|
function parse(data) {
try {
return JSON.parse(data);
} catch (e) {
log('Oops! Some problems parsing this ' + (typeof data ===
|
javascript
|
{
"resource": ""
}
|
q5593
|
setItem
|
train
|
function setItem(key, value) {
var expires = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
if (!isCookieEnabled) {
session.setItem(key, value);
log('I\'ve saved "' + key + '" in a plain object :)', 'warning',
|
javascript
|
{
"resource": ""
}
|
q5594
|
clear
|
train
|
function clear() {
var cookies = isBrowser && document.cookie.split(';');
if (!cookies.length) {
return;
}
for (var i = 0, l = cookies.length; i <
|
javascript
|
{
"resource": ""
}
|
q5595
|
hasLocalStorage
|
train
|
function hasLocalStorage() {
if (!localstorage) {
return false;
}
try {
|
javascript
|
{
"resource": ""
}
|
q5596
|
getItem
|
train
|
function getItem(key) {
var parsed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var fallbackValue = arguments[2];
var result = void 0;
var cookieItem = cookie$1.getItem(key);
var sessionItem = session.getItem(key);
if (!hasLocalStorage()) {
result = cookieItem || sessionItem;
} else {
result = localstorage.getItem(key) || cookieItem || sessionItem;
}
|
javascript
|
{
"resource": ""
}
|
q5597
|
removeItem
|
train
|
function removeItem(key) {
cookie$1.removeItem(key);
session.removeItem(key);
|
javascript
|
{
"resource": ""
}
|
q5598
|
off
|
train
|
function off(type, handler) {
if (all[type]) {
|
javascript
|
{
"resource": ""
}
|
q5599
|
defaultify
|
train
|
function defaultify (obj) {
return Object.keys(self.defaults).reduce(function (acc, key) {
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.