_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q60000
|
authenticate
|
validation
|
function authenticate ({username, password, clientToken, agent}) {
return fetch(`${YGGDRASIL_API}/authenticate`, {
method: 'POST',
body: JSON.stringify({
agent,
username,
password,
clientToken,
requestUser: true
}),
headers: {
'user-agent': USER_AGENT,
'Content-Type': 'application/json',
'accept': 'application/json'
}
})
.then(handleErrors)
.then(res => res.json())
}
|
javascript
|
{
"resource": ""
}
|
q60001
|
isValid
|
validation
|
function isValid ({accessToken, clientToken}) {
return fetch(`${YGGDRASIL_API}/validate`, {
method: 'POST',
body: JSON.stringify({
accessToken,
clientToken
}),
headers: {
'user-agent': USER_AGENT,
'content-type': 'application/json'
}
})
.then(handleErrors)
.then(res => true)
.catch(err => {
if (err.message === 'Invalid token') return false
throw err
})
}
|
javascript
|
{
"resource": ""
}
|
q60002
|
lookupProfileAt
|
validation
|
function lookupProfileAt (name, date, agent = 'minecraft') {
const hasDate = typeof date !== 'undefined'
const query = hasDate
? `/users/profiles/${agent}/${name}?at=${date}`
: `/users/profiles/${agent}/${name}`
return fetch(`${CORE_API}${query}`, {
headers: {
'user-agent': USER_AGENT,
'accept': 'application/json'
}
})
.then(handleErrors)
.then(res => {
if (res.status === 204) throw new Error(`so such name at time: ${name}`)
return res.json()
})
}
|
javascript
|
{
"resource": ""
}
|
q60003
|
setSkin
|
validation
|
function setSkin ({accessToken}, profileId, skinUrl, isSlim = false) {
const params = new URLSearchParams()
params.append('model', isSlim ? 'slim' : '')
params.append('url', skinUrl)
return fetch(`${CORE_API}/user/profile/${profileId}/skin`, {
method: 'POST',
body: params,
headers: {
'user-agent': USER_AGENT,
'authorization': `Bearer ${accessToken}`
}
})
.then(handleErrors)
.then(res => null)
}
|
javascript
|
{
"resource": ""
}
|
q60004
|
coerceControllerAlias
|
validation
|
function coerceControllerAlias(property) {
return computed(property, {
get() {
let controllerName = this.get('controllerName') || this.get('routeName');
let controller = this.get('controller') || this.controllerFor(controllerName);
return controller.get(property);
},
set(key, value) {
let controllerName = this.get('controllerName') || this.get('routeName');
let controller = this.get('controller') || this.controllerFor(controllerName);
controller.set(property, value);
return value;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q60005
|
encode
|
validation
|
function encode() {
var data = this.data;
var length = 11;
var sender = this.sender;
var target = this.target;
var header = new Buffer(9);
var content = !data || isBuffer(data) ? data : this.encode(data);
if (content) length += content.length;
header.writeUInt8(length, 0);
header.writeUInt8(sender.subnet, 1);
header.writeUInt8(sender.id, 2);
header.writeUInt16BE(sender.type, 3);
header.writeUInt16BE(this.code, 5);
header.writeUInt8(target.subnet, 7);
header.writeUInt8(target.id, 8);
return content ? Buffer.concat([header, content]) : header;
}
|
javascript
|
{
"resource": ""
}
|
q60006
|
isValid
|
validation
|
function isValid(message) {
if (!Constants.equals(message.slice(4, 16))) return false;
var checksum = message.readUInt16BE(message.length - 2);
return checksum === crc(message.slice(16, -2));
}
|
javascript
|
{
"resource": ""
}
|
q60007
|
source
|
validation
|
function source(message) {
var ip = [];
for (var i = 0; i < 4; i++) ip.push(message[i]);
return ip.join('.');
}
|
javascript
|
{
"resource": ""
}
|
q60008
|
parse
|
validation
|
function parse(resource) {
if (typeof resource === 'object') return resource;
var config = url.parse(resource);
return {
port: config.port,
device: config.auth,
gateway: config.hostname
};
}
|
javascript
|
{
"resource": ""
}
|
q60009
|
getComponentDescendants
|
validation
|
function getComponentDescendants (root, component, onlyChildren, includeSelf) {
var node = rquery_getDOMNode(component),
descendants = [];
if (onlyChildren) {
descendants = node.children;
} else {
descendants = node.getElementsByTagName('*');
}
// convert to array
descendants = _.toArray(descendants);
if (includeSelf) {
descendants.unshift(rquery_getDOMNode(component));
}
injectCompositeComponents(root, descendants);
return descendants;
}
|
javascript
|
{
"resource": ""
}
|
q60010
|
flushDeferredPadding
|
validation
|
function flushDeferredPadding(blocks) {
if (!padding)
return;
let prevBlock = blocks[blocks.length - 2];
prevBlock.text += padding;
}
|
javascript
|
{
"resource": ""
}
|
q60011
|
validation
|
function(e) {
e.data.handler.over = true;
$.iframeTracker.retrieveFocus();
try {
e.data.handler.overCallback(this, e);
} catch (ex) {}
}
|
javascript
|
{
"resource": ""
}
|
|
q60012
|
validation
|
function(e) {
e.data.handler.over = false;
$.iframeTracker.retrieveFocus();
try {
e.data.handler.outCallback(this, e);
} catch (ex) {}
}
|
javascript
|
{
"resource": ""
}
|
|
q60013
|
validation
|
function() {
if (document.activeElement && document.activeElement.tagName === "IFRAME") {
$.iframeTracker.focusRetriever.focus();
$.iframeTracker.focusRetrieved = true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60014
|
validation
|
function(e) {
for (var i in this.handlersList) {
if (this.handlersList[i].over === true) {
try {
this.handlersList[i].blurCallback(e);
} catch (ex) {}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60015
|
funcWithReturnFromSnippet
|
validation
|
function funcWithReturnFromSnippet(js) {
// auto-"return"
if (js.indexOf('return') === -1) {
if (js.substring(js.length - 1) === ';') {
js = js.substring(0, js.length - 1);
}
js = 'return (' + js + ')';
}
// Expose level definitions to condition func context
var varDefs = [];
Object.keys(upperNameFromLevel).forEach(function (lvl) {
varDefs.push(format('var %s = %d;',
upperNameFromLevel[lvl], lvl));
});
varDefs = varDefs.join('\n') + '\n';
return (new Function(varDefs + js));
}
|
javascript
|
{
"resource": ""
}
|
q60016
|
parseArgv
|
validation
|
function parseArgv(argv) {
var parsed = {
args: [],
help: false,
color: null,
paginate: null,
outputMode: OM_LONG,
jsonIndent: 2,
level: null,
strict: false,
pids: null,
pidsType: null,
timeFormat: TIME_UTC // one of the TIME_ constants
};
// Turn '-iH' into '-i -H', except for argument-accepting options.
var args = argv.slice(2); // drop ['node', 'scriptname']
var newArgs = [];
var optTakesArg = {'d': true, 'o': true, 'c': true, 'l': true, 'p': true};
for (var i = 0; i < args.length; i++) {
if (args[i].charAt(0) === '-' && args[i].charAt(1) !== '-' &&
args[i].length > 2)
{
var splitOpts = args[i].slice(1).split('');
for (var j = 0; j < splitOpts.length; j++) {
newArgs.push('-' + splitOpts[j]);
if (optTakesArg[splitOpts[j]]) {
var optArg = splitOpts.slice(j+1).join('');
if (optArg.length) {
newArgs.push(optArg);
}
break;
}
}
} else {
newArgs.push(args[i]);
}
}
args = newArgs;
// Expose level definitions to condition vm context
var condDefines = [];
Object.keys(upperNameFromLevel).forEach(function (lvl) {
condDefines.push(
format('Object.prototype.%s = %s;', upperNameFromLevel[lvl], lvl));
});
condDefines = condDefines.join('\n') + '\n';
var endOfOptions = false;
while (args.length > 0) {
var arg = args.shift();
switch (arg) {
case '--':
endOfOptions = true;
break;
case '-h': // display help and exit
case '--help':
parsed.help = true;
break;
case '--version':
parsed.version = true;
break;
case '--strict':
parsed.strict = true;
break;
case '--color':
parsed.color = true;
break;
case '--no-color':
parsed.color = false;
break;
case '--pager':
parsed.paginate = true;
break;
case '--no-pager':
parsed.paginate = false;
break;
case '-o':
case '--output':
var name = args.shift();
var idx = name.lastIndexOf('-');
if (idx !== -1) {
var indentation = Number(name.slice(idx+1));
if (! isNaN(indentation)) {
parsed.jsonIndent = indentation;
name = name.slice(0, idx);
}
}
parsed.outputMode = OM_FROM_NAME[name];
if (parsed.outputMode === undefined) {
throw new Error('unknown output mode: "'+name+'"');
}
break;
case '-j': // output with JSON.stringify
parsed.outputMode = OM_JSON;
break;
case '-0':
parsed.outputMode = OM_BUNYAN;
break;
case '-L':
parsed.timeFormat = TIME_LOCAL;
if (!moment) {
throw new Error(
'could not find moment package required for "-L"');
}
break;
case '--time':
var timeArg = args.shift();
switch (timeArg) {
case 'utc':
parsed.timeFormat = TIME_UTC;
break
case 'local':
parsed.timeFormat = TIME_LOCAL;
if (!moment) {
throw new Error('could not find moment package '
+ 'required for "--time=local"');
}
break
case undefined:
throw new Error('missing argument to "--time"');
default:
throw new Error(format('invalid time format: "%s"',
timeArg));
}
break;
case '-p':
if (!parsed.pids) {
parsed.pids = [];
}
var pidArg = args.shift();
var pid = +(pidArg);
if (!isNaN(pid) || pidArg === '*') {
if (parsed.pidsType && parsed.pidsType !== 'num') {
throw new Error(format('cannot mix PID name and '
+ 'number arguments: "%s"', pidArg));
}
parsed.pidsType = 'num';
if (!parsed.pids) {
parsed.pids = [];
}
parsed.pids.push(isNaN(pid) ? pidArg : pid);
} else {
if (parsed.pidsType && parsed.pidsType !== 'name') {
throw new Error(format('cannot mix PID name and '
+ 'number arguments: "%s"', pidArg));
}
parsed.pidsType = 'name';
parsed.pids = pidArg;
}
break;
case '-l':
case '--level':
var levelArg = args.shift();
var level = +(levelArg);
if (isNaN(level)) {
level = +levelFromName[levelArg.toLowerCase()];
}
if (isNaN(level)) {
throw new Error('unknown level value: "'+levelArg+'"');
}
parsed.level = level;
break;
case '-c':
case '--condition':
gUsingConditionOpts = true;
var condition = args.shift();
if (Boolean(process.env.BUNYAN_EXEC &&
process.env.BUNYAN_EXEC === 'vm'))
{
parsed.condVm = parsed.condVm || [];
var scriptName = 'bunyan-condition-'+parsed.condVm.length;
var code = condDefines + condition;
var script;
try {
script = vm.createScript(code, scriptName);
} catch (complErr) {
throw new Error(format('illegal CONDITION code: %s\n'
+ ' CONDITION script:\n'
+ '%s\n'
+ ' Error:\n'
+ '%s',
complErr, indent(code), indent(complErr.stack)));
}
// Ensure this is a reasonably safe CONDITION.
try {
script.runInNewContext(minValidRecord);
} catch (condErr) {
throw new Error(format(
/* JSSTYLED */
'CONDITION code cannot safely filter a minimal Bunyan log record\n'
+ ' CONDITION script:\n'
+ '%s\n'
+ ' Minimal Bunyan log record:\n'
+ '%s\n'
+ ' Filter error:\n'
+ '%s',
indent(code),
indent(JSON.stringify(minValidRecord, null, 2)),
indent(condErr.stack)
));
}
parsed.condVm.push(script);
} else {
parsed.condFuncs = parsed.condFuncs || [];
parsed.condFuncs.push(funcWithReturnFromSnippet(condition));
}
break;
default: // arguments
if (!endOfOptions && arg.length > 0 && arg[0] === '-') {
throw new Error('unknown option "'+arg+'"');
}
parsed.args.push(arg);
break;
}
}
//TODO: '--' handling and error on a first arg that looks like an option.
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
q60017
|
processStdin
|
validation
|
function processStdin(opts, stylize, callback) {
var leftover = ''; // Left-over partial line from last chunk.
var stdin = process.stdin;
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
var lines = chunk.split(/\r\n|\n/);
var length = lines.length;
if (length === 1) {
leftover += lines[0];
return;
}
if (length > 1) {
handleLogLine(null, leftover + lines[0], opts, stylize);
}
leftover = lines.pop();
length -= 1;
for (var i = 1; i < length; i++) {
handleLogLine(null, lines[i], opts, stylize);
}
});
stdin.on('end', function () {
if (leftover) {
handleLogLine(null, leftover, opts, stylize);
leftover = '';
}
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
q60018
|
getPids
|
validation
|
function getPids(cb) {
if (opts.pidsType === 'num') {
return cb(null, opts.pids);
}
if (process.platform === 'sunos') {
execFile('/bin/pgrep', ['-lf', opts.pids],
function (pidsErr, stdout, stderr) {
if (pidsErr) {
warn('bunyan: error getting PIDs for "%s": %s\n%s\n%s',
opts.pids, pidsErr.message, stdout, stderr);
return cb(1);
}
var pids = stdout.trim().split('\n')
.map(function (line) {
return line.trim().split(/\s+/)[0]
})
.filter(function (pid) {
return Number(pid) !== process.pid
});
if (pids.length === 0) {
warn('bunyan: error: no matching PIDs found for "%s"',
opts.pids);
return cb(2);
}
cb(null, pids);
}
);
} else {
var regex = opts.pids;
if (regex && /[a-zA-Z0-9_]/.test(regex[0])) {
// 'foo' -> '[f]oo' trick to exclude the 'grep' PID from its
// own search.
regex = '[' + regex[0] + ']' + regex.slice(1);
}
exec(format('ps -A -o pid,command | grep \'%s\'', regex),
function (pidsErr, stdout, stderr) {
if (pidsErr) {
warn('bunyan: error getting PIDs for "%s": %s\n%s\n%s',
opts.pids, pidsErr.message, stdout, stderr);
return cb(1);
}
var pids = stdout.trim().split('\n')
.map(function (line) {
return line.trim().split(/\s+/)[0];
})
.filter(function (pid) {
return Number(pid) !== process.pid;
});
if (pids.length === 0) {
warn('bunyan: error: no matching PIDs found for "%s"',
opts.pids);
return cb(2);
}
cb(null, pids);
}
);
}
}
|
javascript
|
{
"resource": ""
}
|
q60019
|
processFile
|
validation
|
function processFile(file, opts, stylize, callback) {
var stream = fs.createReadStream(file);
if (/\.gz$/.test(file)) {
stream = stream.pipe(require('zlib').createGunzip());
}
// Manually decode streams - lazy load here as per node/lib/fs.js
var decoder = new (require('string_decoder')
.StringDecoder)('utf8');
streams[file].stream = stream;
stream.on('error', function (err) {
streams[file].done = true;
callback(err);
});
var leftover = ''; // Left-over partial line from last chunk.
stream.on('data', function (data) {
var chunk = decoder.write(data);
if (!chunk.length) {
return;
}
var lines = chunk.split(/\r\n|\n/);
var length = lines.length;
if (length === 1) {
leftover += lines[0];
return;
}
if (length > 1) {
handleLogLine(file, leftover + lines[0], opts, stylize);
}
leftover = lines.pop();
length -= 1;
for (var i = 1; i < length; i++) {
handleLogLine(file, lines[i], opts, stylize);
}
});
stream.on('end', function () {
streams[file].done = true;
if (leftover) {
handleLogLine(file, leftover, opts, stylize);
leftover = '';
} else {
emitNextRecord(opts, stylize);
}
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
q60020
|
MochaWorkerReporter
|
validation
|
function MochaWorkerReporter (runner) {
EVENTS.forEach(function (eventName) {
runner.on(eventName, function (test, error) {
var data = {
'event' : eventName,
'test' : clean(test, error)
};
try {
process.send({
type : 'testResults',
data : data
});
} catch (e) {
console.log('MochaWorkerReporter: Error sending test results.', JSON.stringify(data), e.message, e.stack);
process.exit(1);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q60021
|
CucumberReporter
|
validation
|
function CucumberReporter (eventMediator) {
var options = {
snippets : true,
stream : process.stdout,
useColors : true
};
this.failureCount = 0;
this.eventMediator = eventMediator;
this.formatter = DotFormatter(options);
// all feature files are finished
this.eventMediator.on('end', this.allFeaturesDone.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q60022
|
closest
|
validation
|
function closest (element, selector) {
while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
if (typeof element.matches === 'function' &&
element.matches(selector)) {
return element;
}
element = element.parentNode;
}
}
|
javascript
|
{
"resource": ""
}
|
q60023
|
delegate
|
validation
|
function delegate(elements, selector, type, callback, useCapture) {
// Handle the regular Element usage
if (typeof elements.addEventListener === 'function') {
return _delegate.apply(null, arguments);
}
// Handle Element-less usage, it defaults to global delegation
if (typeof type === 'function') {
// Use `document` as the first parameter, then apply arguments
// This is a short way to .unshift `arguments` without running into deoptimizations
return _delegate.bind(null, document).apply(null, arguments);
}
// Handle Selector-based usage
if (typeof elements === 'string') {
elements = document.querySelectorAll(elements);
}
// Handle Array-like based usage
return Array.prototype.map.call(elements, function (element) {
return _delegate(element, selector, type, callback, useCapture);
});
}
|
javascript
|
{
"resource": ""
}
|
q60024
|
listener
|
validation
|
function listener(element, selector, type, callback) {
return function(e) {
e.delegateTarget = closest_1(e.target, selector);
if (e.delegateTarget) {
callback.call(element, e);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q60025
|
listenNode
|
validation
|
function listenNode(node, type, callback) {
node.addEventListener(type, callback);
return {
destroy: function() {
node.removeEventListener(type, callback);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q60026
|
listenNodeList
|
validation
|
function listenNodeList(nodeList, type, callback) {
Array.prototype.forEach.call(nodeList, function(node) {
node.addEventListener(type, callback);
});
return {
destroy: function() {
Array.prototype.forEach.call(nodeList, function(node) {
node.removeEventListener(type, callback);
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q60027
|
listenSelector
|
validation
|
function listenSelector(selector, type, callback) {
return delegate_1(document.body, selector, type, callback);
}
|
javascript
|
{
"resource": ""
}
|
q60028
|
getAttributeValue
|
validation
|
function getAttributeValue(suffix, element) {
var attribute = 'data-clipboard-' + suffix;
if (!element.hasAttribute(attribute)) {
return;
}
return element.getAttribute(attribute);
}
|
javascript
|
{
"resource": ""
}
|
q60029
|
AssetLoader
|
validation
|
function AssetLoader(manifest, loader) {
this.assets = loadAssets(manifest, loader, function(err) {
if (err) {
console.error(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q60030
|
FontLoader
|
validation
|
function FontLoader(fontFamiliesArray, delegate, timeout) {
// Public
this.delegate = delegate;
this.timeout = (typeof timeout !== "undefined") ? timeout : 3000;
// Private
this._fontFamiliesArray = fontFamiliesArray.slice(0);
this._testContainer = null;
this._adobeBlankSizeWatcher = null;
this._timeoutId = null;
this._intervalId = null;
this._intervalDelay = 50;
this._numberOfLoadedFonts = 0;
this._numberOfFontFamilies = this._fontFamiliesArray.length;
this._fontsMap = {};
this._finished = false;
}
|
javascript
|
{
"resource": ""
}
|
q60031
|
validation
|
function(sizeWatcher) {
var watchedElement = sizeWatcher.getWatchedElement();
if (sizeWatcher === this._adobeBlankSizeWatcher) {
this._adobeBlankLoaded(watchedElement);
} else {
this._elementSizeChanged(watchedElement);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60032
|
SizeWatcher
|
validation
|
function SizeWatcher(element, options) {
this._element = element;
this._delegate = options.delegate;
this._size = null;
this._continuous = !!options.continuous;
this._direction = options.direction ? options.direction : SizeWatcher.directions.both;
this._dimension = options.dimension ? options.dimension : SizeWatcher.dimensions.both;
this._sizeIncreaseWatcherContentElm = null;
this._sizeDecreaseWatcherElm = null;
this._sizeIncreaseWatcherElm = null;
this._state = SizeWatcher.states.initialized;
this._generateScrollWatchers(options.size);
this._appendScrollWatchersToElement(options.container);
}
|
javascript
|
{
"resource": ""
}
|
q60033
|
validation
|
function(prefab) {
/**
* The name of a prefab to instantiate for the particle, as defined in <code>prefabs.json</code>.
* @member {string}
*/
this.prefab = prefab;
/**
* The origin point in which to create particles.
*
* If the origin is a number it represents an entity and a random point inside the entity will be used.
* If origin is a point like <code>{"x": 50, "y": 50}</code> particles will spawn at that position.
* @member {object | number}
*/
this.origin = { "x": 0, "y": 0 };
/**
* How to distribute particles along the {@link module:splat-ecs/lib/particles.Config#arcWidth arcWidth}.
*
* Possible values:
* <dl>
* <dt><code>"even"</code></dt>
* <dd>Distribute the particles evenly along the arc.</dd>
* <dt><code>"random"</code></dt>
* <dd>Scatter the particles on random points of the arc.</dd>
* </dl>
* @member {string}
*/
this.spreadType = "random";
/**
* The direction (an angle in radians) that the particles should move.
* @member {number}
*/
this.angle = 0;
/**
* The width of an arc (represented by an angle in radians) to spread the particles. The arc is centered around {@link module:splat-ecs/lib/particles.Config#angle angle}.
* @member {number}
*/
this.arcWidth = Math.PI / 2;
/**
* The minimum number of particles to create.
* @member {number}
*/
this.qtyMin = 1;
/**
* The maximum number of particles to create.
* @member {number}
*/
this.qtyMax = 1;
/**
* The minimum percentage to scale each particle.
* <ul>
* <li>A scale of 0.5 means the particle will spawn at 50% (half) of the original size.</li>
* <li>A scale of 1 means the particle will spawn at the original size.</li>
* <li>A scale of 2 means the particle will spawn at 200% (double) the original size.</li>
* </ul>
* @member {number}
*/
this.sizeMin = 1;
/**
* The maximum percentage to scale each particle.
* <ul>
* <li>A scale of 0.5 means the particle will spawn at 50% (half) of the original size.</li>
* <li>A scale of 1 means the particle will spawn at the original size.</li>
* <li>A scale of 2 means the particle will spawn at 200% (double) the original size.</li>
* </ul>
* @member {number}
*/
this.sizeMax = 1;
/**
* The minimum velocity to apply to each particle.
* @member {number}
*/
this.velocityMin = 0.5;
/**
* The maximum velocity to apply to each particle.
* @member {number}
*/
this.velocityMax = 0.5;
/**
* The acceleration on the x-axis to apply to each particle.
* @member {number}
*/
this.accelerationX = 0;
/**
* The acceleration on the y-axis to apply to each particle.
* @member {number}
*/
this.accelerationY = 0;
/**
* The minimum life span to apply to each particle.
* @member {number}
*/
this.lifeSpanMin = 0;
/**
* The maximum life span to apply to each particle.
* @member {number}
*/
this.lifeSpanMax = 500;
}
|
javascript
|
{
"resource": ""
}
|
|
q60034
|
centerEntityOnPoint
|
validation
|
function centerEntityOnPoint(game, entity, point) {
var size = game.entities.getComponent(entity, "size");
var position = game.entities.addComponent(entity, "position");
position.x = point.x - (size.width / 2);
position.y = point.y - (size.height / 2);
}
|
javascript
|
{
"resource": ""
}
|
q60035
|
choosePointInEntity
|
validation
|
function choosePointInEntity(game, entity) {
var position = game.entities.getComponent(entity, "position");
var size = game.entities.getComponent(entity, "size");
if (size === undefined) {
return {
"x": position.x,
"y": position.y
};
}
return {
"x": random.inRange(position.x, (position.x + size.width)),
"y": random.inRange(position.y, (position.y + size.height))
};
}
|
javascript
|
{
"resource": ""
}
|
q60036
|
makeBuffer
|
validation
|
function makeBuffer(width, height, drawFun) {
var canvas = makeCanvas(width, height);
var ctx = canvas.getContext("2d");
// when image smoothing is enabled, the image gets blurred and the pixel data isn't correct even when the image shouldn't be scaled which breaks NinePatch
if (platform.isEjecta()) {
ctx.imageSmoothingEnabled = false;
}
drawFun(ctx);
return canvas;
}
|
javascript
|
{
"resource": ""
}
|
q60037
|
flipBufferHorizontally
|
validation
|
function flipBufferHorizontally(buffer) {
return makeBuffer(buffer.width, buffer.height, function(context) {
context.scale(-1, 1);
context.drawImage(buffer, -buffer.width, 0);
});
}
|
javascript
|
{
"resource": ""
}
|
q60038
|
flipBufferVertically
|
validation
|
function flipBufferVertically(buffer) {
return makeBuffer(buffer.width, buffer.height, function(context) {
context.scale(1, -1);
context.drawImage(buffer, 0, -buffer.height);
});
}
|
javascript
|
{
"resource": ""
}
|
q60039
|
rotateClockwise
|
validation
|
function rotateClockwise(buffer) {
var w = buffer.height;
var h = buffer.width;
var w2 = Math.floor(w / 2);
var h2 = Math.floor(h / 2);
return makeBuffer(w, h, function(context) {
context.translate(w2, h2);
context.rotate(Math.PI / 2);
context.drawImage(buffer, -h2, -w2);
});
}
|
javascript
|
{
"resource": ""
}
|
q60040
|
chromeStorageGet
|
validation
|
function chromeStorageGet(keys, callback) {
window.chrome.storage.sync.get(keys, function(data) {
if (window.chrome.runtime.lastError) {
callback(window.chrome.runtime.lastError);
} else {
callback(undefined, data);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q60041
|
chromeStorageSet
|
validation
|
function chromeStorageSet(data, callback) {
window.chrome.storage.sync.set(data, function() {
callback(window.chrome.runtime.lastError);
});
}
|
javascript
|
{
"resource": ""
}
|
q60042
|
SoundManager
|
validation
|
function SoundManager(manifest) {
/**
* A flag signifying if sounds have been muted through {@link SoundManager#mute}.
* @member {boolean}
* @private
*/
this.muted = false;
/**
* A key-value object that stores named looping sounds.
* @member {object}
* @private
*/
this.looping = {};
/**
* The Web Audio API AudioContext
* @member {external:AudioContext}
* @private
*/
this.context = new window.AudioContext();
this.gainNode = this.context.createGain();
this.gainNode.connect(this.context.destination);
this.volume = this.gainNode.gain.value;
this.installSafariWorkaround();
this.assets = new AssetLoader(manifest, loadSound.bind(undefined, this.context));
}
|
javascript
|
{
"resource": ""
}
|
q60043
|
validation
|
function (program, callback) {
var config = configHelpers.getConfig();
config.plugins = config.plugins || {};
var loadPlugin = function (pluginName, cb) {
pluginHelpers.loadPlugin(pluginName, program, cb);
};
Object.keys(config.plugins).forEach(loadPlugin);
nodeHelpers.invoke(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q60044
|
validation
|
function (program, app, callback) {
var attachPlugin = function (pluginName, cb) {
pluginHelpers.start(pluginName, program, app, cb);
};
var plugins = Object.keys(pluginHelpers.loadedPlugins)
async.eachSeries(plugins, attachPlugin, function() {
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60045
|
validation
|
function (callback) {
var plugins = Object.keys(pluginHelpers.loadedPlugins || {});
async.eachSeries(plugins, pluginHelpers.stop, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q60046
|
validation
|
function (program, callback) {
var cozyLight = require('./cozy-light');
applicationHelpers.resetDefaultPort();
cozyLight.setStarted();
// start app
var app = express();
var morgand = morgan('combined');
if (expressLog) {
app.use(morgand);
}
pluginHelpers.startAll(program, app, function(){
mainAppHelper.start(app);
applicationHelpers.startAll(function() {
// always connect it after the proxy
// https://github.com/nodejitsu/node-http-proxy/issues/180
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.use(urlencodedParser);
app.use(jsonParser);
nodeHelpers.invoke(callback, null, app, server);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60047
|
validation
|
function (apporplugin) {
try {
configHelpers.enable(apporplugin);
logger.info(apporplugin + ' enabled');
} catch (err) {
logger.error(
'Cannot enable given app or plugin, ' +
apporplugin +
' cannot find it in the config file.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60048
|
validation
|
function (apporplugin) {
try {
configHelpers.disable(apporplugin);
logger.info(apporplugin + ' disabled');
} catch (err) {
logger.error(
'Cannot disable given app or plugin, ' +
apporplugin +
' cannot find it in the config file.');
logger.raw(err);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60049
|
validation
|
function (callback) {
var cozyLight = require('./cozy-light');
if (cozyLight.getStatus() === 'started') {
cozyLight.setStopped();
logger.info('Stopping apps...');
return applicationHelpers.stopAll(function (appErr) {
if (appErr) {
logger.error('An error occurred while stopping applications');
logger.raw(appErr);
}
logger.info('Stopping plugins...');
pluginHelpers.stopAll(function (pluginErr) {
if (pluginErr) {
logger.error('An error occurred while stopping plugins');
logger.raw(pluginErr);
}
logger.info('Stopping server...');
var timeout = nodeHelpers.throwTimeout(
'main server is too slow to stop...', 5000);
mainAppHelper.stop(function(){
clearTimeout(timeout);
logger.info('\t' + symbols.ok + '\tmain server');
nodeHelpers.invoke(callback);
});
});
});
}
logger.debug('Apps already stopped');
return nodeHelpers.invoke(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q60050
|
validation
|
function (callback) {
var cozyLight = require('./cozy-light');
logger.info('Restarting...');
actions.stop(function(){
configHelpers.loadConfigFile();
cozyLight.routes = {};
logger.info('Starting all apps...');
pluginHelpers.loadAll(this.program, function() {
actions.start(this.program, function(){
logger.info('...Cozy Light was properly restarted.');
nodeHelpers.invoke(callback);
actionsEvent.emit('restarted');
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60051
|
validation
|
function (app, callback) {
var cozyLight = require('./cozy-light');
var config = configHelpers.getConfig();
logger.info('Uninstalling ' + app + '...');
if (config.apps[app] === undefined) {
logger.error(app + ' is not installed.');
nodeHelpers.invoke(callback, true);
} else {
var module = config.apps[app].name;
npmHelpers.uninstall(module, function removeAppFromConfig (err) {
if (err) {
logger.raw(err);
logger.error('npm did not uninstall ' + app + ' correctly.');
nodeHelpers.invoke(callback, err);
} else {
logger.info(app + ' successfully uninstalled.');
configHelpers.watcher.one(callback);
configHelpers.removeApp(app);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60052
|
validation
|
function (plugin, callback){
var cozyLight = require('./cozy-light');
var config = configHelpers.getConfig();
logger.info('Removing ' + plugin + '...');
if (config.plugins[plugin] === undefined) {
logger.error(plugin + ' is not installed.');
nodeHelpers.invoke(callback, true);
} else {
var module = config.plugins[plugin].name;
npmHelpers.uninstall(module, function removePluginFromConfig (err) {
if (err) {
logger.raw(err);
logger.error('npm did not uninstall ' + plugin + ' correctly.');
nodeHelpers.invoke(callback, err);
} else {
logger.info(plugin + ' successfully uninstalled.');
pluginHelpers.stop(plugin, function(){
pluginHelpers.unloadPlugin(plugin);
configHelpers.watcher.one(callback);
configHelpers.removePlugin(plugin);
});
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60053
|
validation
|
function (distroName, actions, callback) {
if (distros[distroName] !== undefined) {
var distro = distros[distroName];
logger.info('Installing plugins...');
async.eachSeries(distro.plugins, function addPlugin (pluginName, cb) {
actions.installPlugin(pluginName, cb);
}, function installApps (err) {
if (err) {
callback(err);
} else {
logger.info('Installing apps...');
async.eachSeries(distro.apps, function addApp (appName, cb) {
actions.installApp(appName, cb);
}, callback);
}
});
} else {
throw new Error('Unknown distro, can\'t install it');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60054
|
validation
|
function (distroName) {
logger.raw('\n\x1B[36m* ' + distroName + '\x1B[39m');
var logAttributeList = function (key) {
logger.raw(' \x1B[32m' + key + ':\x1B[39m');
var list = distros[distroName][key];
if (list !== undefined && list.length > 0) {
list.forEach(function displayListElement (keyName) {
logger.raw(' - ' + keyName.split('/')[1]);
});
} else {
logger.raw(' no ' + key);
}
};
logAttributeList('plugins');
logAttributeList('apps');
}
|
javascript
|
{
"resource": ""
}
|
|
q60055
|
saveWallet
|
validation
|
function saveWallet(filename, walletData) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, JSON.stringify(walletData, null, 2), function(err) {
if (err) return reject(console.error(err))
//console.log(`${name}.json written successfully.`)
return resolve()
})
})
}
|
javascript
|
{
"resource": ""
}
|
q60056
|
openWallet
|
validation
|
function openWallet(filename) {
try {
// Delete the cached copy of the wallet. This allows testing of list-wallets.
delete require.cache[require.resolve(filename)]
const walletInfo = require(filename)
return walletInfo
} catch (err) {
throw new Error(`Could not open ${filename}`)
}
}
|
javascript
|
{
"resource": ""
}
|
q60057
|
changeAddrFromMnemonic
|
validation
|
function changeAddrFromMnemonic(walletInfo, index, BITBOX) {
// root seed buffer
const rootSeed = BITBOX.Mnemonic.toSeed(walletInfo.mnemonic)
// master HDNode
if (walletInfo.network === "testnet")
var masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, "testnet")
else var masterHDNode = BITBOX.HDNode.fromSeed(rootSeed)
// HDNode of BIP44 account
const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
// derive the first external change address HDNode which is going to spend utxo
const change = BITBOX.HDNode.derivePath(account, `0/${index}`)
return change
}
|
javascript
|
{
"resource": ""
}
|
q60058
|
getUTXOs
|
validation
|
async function getUTXOs(walletInfo, BITBOX) {
try {
const retArray = []
// Loop through each address that has a balance.
for (var i = 0; i < walletInfo.hasBalance.length; i++) {
const thisAddr = walletInfo.hasBalance[i].cashAddress
// Get the UTXOs for that address.
const u = await BITBOX.Address.utxo([thisAddr])
//console.log(`u for ${thisAddr}: ${util.inspect(u[0])}`)
// Loop through each UXTO returned
for (var j = 0; j < u[0].length; j++) {
const thisUTXO = u[0][j]
//console.log(`thisUTXO: ${util.inspect(thisUTXO)}`)
// Add the HD node index to the UTXO for use later.
thisUTXO.hdIndex = walletInfo.hasBalance[i].index
// Add the UTXO to the array if it has at least one confirmation.
if (thisUTXO.confirmations > 0) retArray.push(thisUTXO)
}
}
return retArray
} catch (err) {
console.log(`Error in getUTXOs.`)
throw err
}
}
|
javascript
|
{
"resource": ""
}
|
q60059
|
validation
|
function (cozyHome, port) {
fs.mkdirsSync(cozyHome);
configHelpers.setHomePath(cozyHome);
configHelpers.setMainAppPort(parseInt(port));
configHelpers.setDefaultAppsPort(parseInt(port) + 100);
configHelpers.copyDependency('pouchdb');
configHelpers.createConfigFile();
configHelpers.watcher = configWatcher;
configHelpers.watcher.init(configHelpers.getConfigPath());
return configHelpers.loadConfigFile();
}
|
javascript
|
{
"resource": ""
}
|
|
q60060
|
validation
|
function () {
var filePath = configHelpers.getConfigPath();
config = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
return config;
}
|
javascript
|
{
"resource": ""
}
|
|
q60061
|
validation
|
function () {
var configString = JSON.stringify(config, null, 2);
fs.writeFileSync(configHelpers.getConfigPath(), configString);
}
|
javascript
|
{
"resource": ""
}
|
|
q60062
|
validation
|
function () {
var exists = fs.existsSync(configHelpers.getConfigPath());
if (!exists) {
config = { apps: {}, plugins: {} };
configHelpers.saveConfig();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60063
|
validation
|
function (name) {
var destPath = configHelpers.modulePath(name);
var sourcePath = pathExtra.join(__dirname, '..', 'node_modules', name);
if (!fs.existsSync(destPath)) {
fs.copySync(sourcePath, destPath);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60064
|
validation
|
function (app, manifest) {
if (manifest.type === undefined) {
manifest.type = 'classic';
}
config.apps[app] = {
name: manifest.name,
displayName: manifest.displayName,
version: manifest.version,
description: manifest.description,
type: manifest.type
};
configHelpers.saveConfig();
}
|
javascript
|
{
"resource": ""
}
|
|
q60065
|
validation
|
function (app) {
var ret = false;
if (config.apps[app] !== undefined) {
delete config.apps[app];
configHelpers.saveConfig();
ret = true;
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q60066
|
validation
|
function (plugin, manifest) {
if (config.plugins === undefined) {
config.plugins = {};
}
config.plugins[plugin] = {
name: manifest.name,
displayName: manifest.displayName,
version: manifest.version,
description: manifest.description
};
configHelpers.saveConfig();
}
|
javascript
|
{
"resource": ""
}
|
|
q60067
|
validation
|
function (plugin) {
var ret = false;
if (config.plugins[plugin] !== undefined) {
delete config.plugins[plugin];
configHelpers.saveConfig();
ret = true;
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q60068
|
validation
|
function (apporplugin) {
if (config.plugins[apporplugin] !== undefined) {
config.plugins[apporplugin].disabled = undefined;
configHelpers.saveConfig();
} else if (config.apps[apporplugin] !== undefined) {
config.apps[apporplugin].disabled = undefined;
configHelpers.saveConfig();
} else {
throw new Error(
'Cannot enable, given app or plugin ' +
apporplugin +
' is not configured.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60069
|
validation
|
function () {
var plugins = {};
Object.keys(config.plugins || {}).forEach(function(name){
var template = '';
//if (loadedPlugins[name] && loadedPlugins[name].getTemplate) {
// template = loadedPlugins[name].getTemplate(config);
//}
plugins[name] = {
name: config.plugins[name].name,
displayName: config.plugins[name].displayName,
version: config.plugins[name].version,
template: template
};
});
return plugins;
}
|
javascript
|
{
"resource": ""
}
|
|
q60070
|
validation
|
function () {
var apps = {};
var baseUrl = configHelpers.getServerUrl();
Object.keys(config.apps || {}).forEach(function(name){
apps[name] = {
name: config.apps[name].name,
displayName: config.apps[name].displayName,
version: config.apps[name].version,
url: baseUrl + '/apps/' + config.apps[name].name + '/'
};
});
return apps;
}
|
javascript
|
{
"resource": ""
}
|
|
q60071
|
validation
|
function (app, callback) {
var options = {
local: true,
dir: configHelpers.getModulesPath(),
prefix: ''
};
npm.load(options, function () {
app = pathExtra.resolve(npmHelpers.initialWd, app);
npm.commands.link([app], callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60072
|
validation
|
function (app, callback) {
var options = {
dir: configHelpers.getModulesPath(),
prefix: ''
};
npm.load(options, function () {
npm.commands.uninstall([app], callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60073
|
validation
|
function (app, callback) {
var appPath = pathExtra.resolve(npmHelpers.initialWd, app);
var manifestPath = pathExtra.join(appPath, 'package.json');
if (fs.existsSync(appPath) && fs.existsSync(manifestPath)) {
fs.readFile(manifestPath, function checkError (err, manifest) {
if (err) {
logger.error(err);
nodeHelpers.invoke(callback, err);
} else {
nodeHelpers.invoke(callback, err, JSON.parse(manifest), 'file');
}
});
} else {
var client = request.newClient('https://raw.githubusercontent.com/');
/* Checking if a branch of the github repo is specified
* within the application path parameter (separated with a @).
*/
if (app.indexOf('@') > 1) {
// if a branch is specified, we build the url with it.
var manifestUrl = app.split('@')[0] + '/' + app.split('@')[1] + '/package.json';
} else {
// if no branch is specified, we build the url with master branch.
var manifestUrl = app + '/master/package.json';
}
console.log(manifestUrl);
client.get(manifestUrl, function (err, res, manifest) {
if (err) {
logger.error(err);
nodeHelpers.invoke(callback, err);
} else if (res.statusCode !== 200) {
logger.error(err);
nodeHelpers.invoke(callback, err);
} else {
nodeHelpers.invoke(callback, err, manifest, 'url');
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60074
|
validation
|
function (msg) {
// Convert binary blobs into native buffers pre-send
if (msg && msg.message && msg.message.message &&
msg.message.message.binary) {
var out = [], i = 0;
for (i = 0; i < msg.message.message.binary.length; i += 1) {
out.push(new Buffer(new Uint8Array(msg.message.message.binary[i])));
}
msg.message.message.binary = out;
}
process.send(msg);
}
|
javascript
|
{
"resource": ""
}
|
|
q60075
|
validation
|
function (script) {
var file, name;
try {
//TODO: enforce constrained location of loaded files.
if (script.indexOf('node://') === 0) {
name = script.substr(7);
}
file = fs.readFileSync(name);
vm.runInContext(file, freedomVM, name);
} catch (e) {
console.error(e);
process.exit(1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60076
|
sortPitches
|
validation
|
function sortPitches (pitches) {
return pitches.map(Pitch).sort(function (a, b) {
return a - b
}).map(function (pitch) {
return pitch.sciPitch()
})
}
|
javascript
|
{
"resource": ""
}
|
q60077
|
parseNavItem
|
validation
|
function parseNavItem (item) {
if (item.route === req.path) {
item.isActive = true;
}
// replace object by array structure
var childArray = [];
for (var child in item.children) {
var subItem = parseNavItem( item.children[ child ] );
if (subItem.isActive || subItem.hasActiveChildren) {
item.hasActiveChildren = true;
}
// check if user can access item
if (userHasAccess(subItem)) {
childArray.push(subItem);
}
}
// sort by _w
childArray.sort(function (a, b) { return a._w - b._w });
item.children = childArray;
return item;
}
|
javascript
|
{
"resource": ""
}
|
q60078
|
userHasAccess
|
validation
|
function userHasAccess (item) {
if (typeof item.isSecure !== 'boolean' || item.isSecure === false) {
// page has no security settings or false, let user pass
return true;
} else {
// page is secured, check if user has access
var pageRoles = item.roles;
debug('pageRoles', item.title, pageRoles)
if (Array.isArray(pageRoles) && pageRoles.length === 0) {
// page is secured, but requires no specific role
if (req.session.user) {
// user is authenticated, let pass
return true;
} else {
// user is not authenticated, reject
return false
}
}
if (!req.session.user || !req.session.user.roleIds) {
// user session does not exist, skip
return false;
}
// make sure roleIds are strings (on first request they are objects)
var userRoles = [];
var sessionRoleIds = req.session.user.roleIds;
for (var r in sessionRoleIds) {
userRoles.push(sessionRoleIds[r].toString());
}
// compare required roles and user roles
for (var r in pageRoles) {
var pageRoleId = pageRoles[r].toString();
if (userRoles.indexOf(pageRoleId) !== -1) {
// user has role, let pass
return true;
}
}
}
// all pass rules failed, reject user
return false;
}
|
javascript
|
{
"resource": ""
}
|
q60079
|
validation
|
function(scope){
if(!scope) throw('textAngular Error: A toolbar requires a scope');
if(!scope.name || scope.name === '') throw('textAngular Error: A toolbar requires a name');
if(toolbars[scope.name]) throw('textAngular Error: A toolbar with name "' + scope.name + '" already exists');
toolbars[scope.name] = scope;
angular.forEach(editors, function(_editor){
_editor._registerToolbar(scope);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60080
|
validation
|
function(name){
var result = [], _this = this;
angular.forEach(this.retrieveEditor(name).toolbars, function(name){
result.push(_this.retrieveToolbar(name));
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q60081
|
validation
|
function(newTaTools){
// pass a partial struct of the taTools, this allows us to update the tools on the fly, will not change the defaults.
var _this = this;
angular.forEach(newTaTools, function(_newTool, key){
_this.updateToolDisplay(key, _newTool);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60082
|
validation
|
function(toolKey, _newTool){
var _this = this;
angular.forEach(toolbars, function(toolbarScope, toolbarKey){
_this.updateToolbarToolDisplay(toolbarKey, toolKey, _newTool);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60083
|
validation
|
function(toolbarKey, toolKey, _newTool){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, _newTool);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
}
|
javascript
|
{
"resource": ""
}
|
|
q60084
|
validation
|
function(toolbarKey, toolKey){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, taTools[toolKey], true);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
}
|
javascript
|
{
"resource": ""
}
|
|
q60085
|
validation
|
function(toolKey){
delete taTools[toolKey];
angular.forEach(toolbars, function(toolbarScope){
delete toolbarScope.tools[toolKey];
for(var i = 0; i < toolbarScope.toolbar.length; i++){
var toolbarIndex;
for(var j = 0; j < toolbarScope.toolbar[i].length; j++){
if(toolbarScope.toolbar[i][j] === toolKey){
toolbarIndex = {
group: i,
index: j
};
break;
}
if(toolbarIndex !== undefined) break;
}
if(toolbarIndex !== undefined){
toolbarScope.toolbar[toolbarIndex.group].slice(toolbarIndex.index, 1);
toolbarScope._$element.children().eq(toolbarIndex.group).children().eq(toolbarIndex.index).remove();
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60086
|
validation
|
function(toolKey, toolDefinition, group, index){
taRegisterTool(toolKey, toolDefinition);
angular.forEach(toolbars, function(toolbarScope){
toolbarScope.addTool(toolKey, toolDefinition, group, index);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60087
|
validation
|
function(toolKey, toolDefinition, toolbarKey, group, index){
taRegisterTool(toolKey, toolDefinition);
toolbars[toolbarKey].addTool(toolKey, toolDefinition, group, index);
}
|
javascript
|
{
"resource": ""
}
|
|
q60088
|
validation
|
function(element, attribute){
var resultingElements = [];
var childNodes = element.children();
if(childNodes.length){
angular.forEach(childNodes, function(child){
resultingElements = resultingElements.concat(taDOM.getByAttribute(angular.element(child), attribute));
});
}
if(element.attr(attribute) !== undefined) resultingElements.push(element);
return resultingElements;
}
|
javascript
|
{
"resource": ""
}
|
|
q60089
|
validation
|
function (elem, eventName, callback) {
var listener = function (event) {
event = event || window.event;
var target = event.target || event.srcElement;
var block = callback.apply(elem, [event, target]);
if (block === false) {
if (!!event.preventDefault) event.preventDefault();
else {
event.returnValue = false;
event.cancelBubble = true;
}
}
return block;
};
if (elem.attachEvent) { // IE only. The "on" is mandatory.
elem.attachEvent("on" + eventName, listener);
} else { // Other browsers.
elem.addEventListener(eventName, listener, false);
}
return listener;
}
|
javascript
|
{
"resource": ""
}
|
|
q60090
|
validation
|
function (elem, event, listener) {
if (elem.detachEvent) { // IE only. The "on" is mandatory.
elem.detachEvent("on" + event, listener);
} else { // Other browsers.
elem.removeEventListener(event, listener, false);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60091
|
addOrSubtractDurationFromMoment
|
validation
|
function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
var milliseconds = duration._milliseconds,
days = duration._days,
months = duration._months,
minutes,
hours,
currentDate;
if (milliseconds) {
mom._d.setTime(+mom._d + milliseconds * isAdding);
}
// store the minutes and hours so we can restore them
if (days || months) {
minutes = mom.minute();
hours = mom.hour();
}
if (days) {
mom.date(mom.date() + days * isAdding);
}
if (months) {
mom.month(mom.month() + months * isAdding);
}
if (milliseconds && !ignoreUpdateOffset) {
moment.updateOffset(mom);
}
// restore the minutes and hours after possibly changing dst
if (days || months) {
mom.minute(minutes);
mom.hour(hours);
}
}
|
javascript
|
{
"resource": ""
}
|
q60092
|
getLangDefinition
|
validation
|
function getLangDefinition(key) {
if (!key) {
return moment.fn._lang;
}
if (!languages[key] && hasModule) {
try {
require('./lang/' + key);
} catch (e) {
// call with no params to set to default
return moment.fn._lang;
}
}
return languages[key];
}
|
javascript
|
{
"resource": ""
}
|
q60093
|
formatMoment
|
validation
|
function formatMoment(m, format) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return m.lang().longDateFormat(input) || input;
}
while (i-- && localFormattingTokens.test(format)) {
format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
}
if (!formatFunctions[format]) {
formatFunctions[format] = makeFormatFunction(format);
}
return formatFunctions[format](m);
}
|
javascript
|
{
"resource": ""
}
|
q60094
|
addTimeToArrayFromToken
|
validation
|
function addTimeToArrayFromToken(token, input, config) {
var a, datePartArray = config._a;
switch (token) {
// MONTH
case 'M' : // fall through to MM
case 'MM' :
datePartArray[1] = (input == null) ? 0 : ~~input - 1;
break;
case 'MMM' : // fall through to MMMM
case 'MMMM' :
a = getLangDefinition(config._l).monthsParse(input);
// if we didn't find a month name, mark the date as invalid.
if (a != null) {
datePartArray[1] = a;
} else {
config._isValid = false;
}
break;
// DAY OF MONTH
case 'D' : // fall through to DDDD
case 'DD' : // fall through to DDDD
case 'DDD' : // fall through to DDDD
case 'DDDD' :
if (input != null) {
datePartArray[2] = ~~input;
}
break;
// YEAR
case 'YY' :
datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
break;
case 'YYYY' :
case 'YYYYY' :
datePartArray[0] = ~~input;
break;
// AM / PM
case 'a' : // fall through to A
case 'A' :
config._isPm = getLangDefinition(config._l).isPM(input);
break;
// 24 HOUR
case 'H' : // fall through to hh
case 'HH' : // fall through to hh
case 'h' : // fall through to hh
case 'hh' :
datePartArray[3] = ~~input;
break;
// MINUTE
case 'm' : // fall through to mm
case 'mm' :
datePartArray[4] = ~~input;
break;
// SECOND
case 's' : // fall through to ss
case 'ss' :
datePartArray[5] = ~~input;
break;
// MILLISECOND
case 'S' :
case 'SS' :
case 'SSS' :
datePartArray[6] = ~~ (('0.' + input) * 1000);
break;
// UNIX TIMESTAMP WITH MS
case 'X':
config._d = new Date(parseFloat(input) * 1000);
break;
// TIMEZONE
case 'Z' : // fall through to ZZ
case 'ZZ' :
config._useUTC = true;
config._tzm = timezoneMinutesFromString(input);
break;
}
// if the input is null, the date is not valid
if (input == null) {
config._isValid = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q60095
|
makeDateFromStringAndFormat
|
validation
|
function makeDateFromStringAndFormat(config) {
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var tokens = config._f.match(formattingTokens),
string = config._i,
i, parsedInput;
config._a = [];
for (i = 0; i < tokens.length; i++) {
parsedInput = (getParseRegexForToken(tokens[i], config).exec(string) || [])[0];
if (parsedInput) {
string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
}
// don't parse if its not a known token
if (formatTokenFunctions[tokens[i]]) {
addTimeToArrayFromToken(tokens[i], parsedInput, config);
}
}
// add remaining unparsed input to the string
if (string) {
config._il = string;
}
// handle am pm
if (config._isPm && config._a[3] < 12) {
config._a[3] += 12;
}
// if is 12 am, change hours to 0
if (config._isPm === false && config._a[3] === 12) {
config._a[3] = 0;
}
// return
dateFromArray(config);
}
|
javascript
|
{
"resource": ""
}
|
q60096
|
makeDateFromString
|
validation
|
function makeDateFromString(config) {
var i,
string = config._i,
match = isoRegex.exec(string);
if (match) {
// match[2] should be "T" or undefined
config._f = 'YYYY-MM-DD' + (match[2] || " ");
for (i = 0; i < 4; i++) {
if (isoTimes[i][1].exec(string)) {
config._f += isoTimes[i][0];
break;
}
}
if (parseTokenTimezone.exec(string)) {
config._f += " Z";
}
makeDateFromStringAndFormat(config);
} else {
config._d = new Date(string);
}
}
|
javascript
|
{
"resource": ""
}
|
q60097
|
_loadProcessor
|
validation
|
function _loadProcessor(processorName) {
const compatibleVersion = compatibleProcessors[processorName]
// Check if module is compatible
if(compatibleVersion === undefined) {
const error = new Error(`Processor ${processorName} is not supported yet.`)
error.code = 'MODULE_NOT_SUPPORTED'
throw error
}
return require(`./processors/${processorName}`)(_loadModule(processorName))
}
|
javascript
|
{
"resource": ""
}
|
q60098
|
getJson
|
validation
|
function getJson(filename, cb) {
fs.readFile(filename, function(err, data) {
if (err) return cb(err, null)
try {
var json = JSON.parse(data)
cb(null, json)
} catch(e) {
cb(e, null)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q60099
|
sauceConfigured
|
validation
|
function sauceConfigured(config) {
var sauceAccessKey = config.access_key
var sauceUsername = config.username
if (!sauceAccessKey || !sauceUsername) {
return false
}
return true
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.