_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q47400
|
train
|
function(action) {
//UR
if (!window.URL || !window.URL.createObjectURL) {
window.URL = window.URL || {};
window.URL.createObjectURL = function(obj) {
return obj;
};
}
if (_browser.supported) {
var newVideo = false;
navigator.getUserMedia = navigator.getUserMedia || navigator.oGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
_readyCb = function() {
try {
if (action === 'stop') {
_stop = true;
icon.reset();
_stop = false;
return;
}
newVideo = document.createElement('video');
newVideo.width = _w;
newVideo.height = _h;
navigator.getUserMedia({
video : true,
audio : false
}, function(stream) {
newVideo.src = URL.createObjectURL(stream);
newVideo.play();
drawVideo(newVideo);
}, function() {
});
} catch(e) {
throw 'Error setting webcam. Message: ' + e.message;
}
};
if (_ready) {
_readyCb();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47401
|
train
|
function() {
var link = document.getElementsByTagName('head')[0].getElementsByTagName('link');
for (var l = link.length, i = (l - 1); i >= 0; i--) {
if ((/(^|\s)icon(\s|$)/i).test(link[i].getAttribute('rel'))) {
return link[i];
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q47402
|
train
|
function(word) {
var h = 0;
for (var i = 0; i < word.length; i++) {
h = word.charCodeAt(i) + ((h << 5) - h);
}
return h;
}
|
javascript
|
{
"resource": ""
}
|
|
q47403
|
train
|
function(color, prc) {
var num = parseInt(color, 16),
amt = Math.round(2.55 * prc),
R = (num >> 16) + amt,
G = (num >> 8 & 0x00FF) + amt,
B = (num & 0x0000FF) + amt;
return (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
(G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
(B < 255 ? B < 1 ? 0 : B : 255))
.toString(16)
.slice(1);
}
|
javascript
|
{
"resource": ""
}
|
|
q47404
|
train
|
function(i) {
var color = ((i >> 24) & 0xFF).toString(16) +
((i >> 16) & 0xFF).toString(16) +
((i >> 8) & 0xFF).toString(16) +
(i & 0xFF).toString(16);
return color;
}
|
javascript
|
{
"resource": ""
}
|
|
q47405
|
swaptitle
|
train
|
function swaptitle(title){
if(a.length===0){
a = [document.title];
}
a.push(title);
if(!iv){
iv = setInterval(function(){
// has document.title changed externally?
if(a.indexOf(document.title) === -1 ){
// update the default title
a[0] = document.title;
}
document.title = a[++i%a.length];
}, 1000);
}
}
|
javascript
|
{
"resource": ""
}
|
q47406
|
addEvent
|
train
|
function addEvent(el,name,func){
if(name.match(" ")){
var a = name.split(' ');
for(var i=0;i<a.length;i++){
addEvent( el, a[i], func);
}
}
if(el.addEventListener){
el.removeEventListener(name, func, false);
el.addEventListener(name, func, false);
}
else {
el.detachEvent('on'+name, func);
el.attachEvent('on'+name, func);
}
}
|
javascript
|
{
"resource": ""
}
|
q47407
|
match
|
train
|
function match(word, array, caseSensitive) {
return $.grep(
array,
function(w) {
if (caseSensitive) {
return !w.indexOf(word);
} else {
return !w.toLowerCase().indexOf(word.toLowerCase());
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
q47408
|
placeholder
|
train
|
function placeholder(word) {
var input = this;
var clone = input.prev(".hint");
input.css({
backgroundColor: "transparent",
position: "relative",
});
// Lets create a clone of the input if it does
// not already exist.
if (!clone.length) {
input.wrap(
$("<div>").css({position: "relative", height: input.css("height")})
);
clone = input
.clone()
.attr("tabindex", -1)
.removeAttr("id name placeholder")
.addClass("hint")
.insertBefore(input);
clone.css({
position: "absolute",
});
}
var hint = "";
if (typeof word !== "undefined") {
var value = input.val();
hint = value + word.substr(value.split(/ |\n/).pop().length);
}
clone.val(hint);
}
|
javascript
|
{
"resource": ""
}
|
q47409
|
select
|
train
|
function select(word) {
var input = this;
var value = input.val();
if (word) {
input.val(
value
+ word.substr(value.split(/ |\n/).pop().length)
);
// Select hint.
input[0].selectionStart = value.length;
}
}
|
javascript
|
{
"resource": ""
}
|
q47410
|
cacheTracksArray
|
train
|
function cacheTracksArray(self) {
self.tracksInOrder = Object.keys(self.playlist).map(trackById);
self.tracksInOrder.sort(asc);
self.tracksInOrder.forEach(function(track, index) {
track.index = index;
});
function asc(a, b) {
return operatorCompare(a.sortKey, b.sortKey);
}
function trackById(id) {
return self.playlist[id];
}
}
|
javascript
|
{
"resource": ""
}
|
q47411
|
sortTracks
|
train
|
function sortTracks(tracks) {
var lib = new MusicLibraryIndex();
tracks.forEach(function(track) {
lib.addTrack(track);
});
lib.rebuildTracks();
var results = [];
lib.artistList.forEach(function(artist) {
artist.albumList.forEach(function(album) {
album.trackList.forEach(function(track) {
results.push(track);
});
});
});
return results;
}
|
javascript
|
{
"resource": ""
}
|
q47412
|
train
|
function(r, n) {
/* the Raphael set is obligatory, containing all you want to display */
var set = r.set().push(
/* custom objects go here */
r.rect(n.point[0]-30, n.point[1]-13, 50, 50)
.attr({"fill": "#fa8", "stroke-width": 2, r: 9}))
.push(r.text(n.point[0], n.point[1] + 15, n.id)
.attr({"font-size":"20px"}));
return set;
}
|
javascript
|
{
"resource": ""
}
|
|
q47413
|
prefix
|
train
|
function prefix(p) {
/* pi contains the computed skip marks */
var pi = [0],
k = 0;
for (q = 1; q < p.length; q++) {
while (k > 0 && p.charAt(k) !== p.charAt(q)) {
k = pi[k - 1];
}if (p.charAt(k) === p.charAt(q)) {
k++;
}
pi[q] = k;
}
return pi;
}
|
javascript
|
{
"resource": ""
}
|
q47414
|
nextTile
|
train
|
function nextTile()
{
clog('nextTile');
rect.emit('tile', tile);
tile = {};
if (rect.tilex < rect.widthTiles)
{
rect.tilex++;
//clog([rect.tilex, rect.tiley]);
return cli.readHextileTile(rect, cb);
} else {
clog('===================== new row! ' + rect.tiley);
rect.tilex = 0;
if (rect.tiley < rect.heightTiles)
{
rect.tiley++;
//clog([rect.tilex, rect.tiley]);
return cli.readHextileTile(rect, cb);
} else {
clog('====================')
clog(rect);
return cb();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47415
|
train
|
function(id, parentId, x, y, width, height, borderWidth, depth, _class, visual, values) {
if (borderWidth === undefined)
borderWidth = 0;
if (depth === undefined)
depth = 0;
if (_class === undefined)
_class = 0;
if (visual === undefined)
visual = 0;
if (values === undefined)
values = {}
var format = 'CCSLLssSSSSLL';
// TODO: slice from function arguments?
// TODO: the code is a little bit mess
// additional values need to be packed in the following way:
// bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply
// values list (bytes #32 .. #32+4*num_values) in order of corresponding bits TODO: it's actually not 4*num. Some values are 4b ytes, some - 1 byte
var vals = packValueMask('CreateWindow', values);
var packetLength = 8 + (values ? vals[2].length : 0);
var args = [1, depth, packetLength, id, parentId, x, y, width, height, borderWidth, _class, visual];
format += vals[0];
args.push(vals[1]);
args = args.concat(vals[2]);
return [format, args];
}
|
javascript
|
{
"resource": ""
}
|
|
q47416
|
leftPad
|
train
|
function leftPad(n, prefix, maxN) {
const s = n.toString();
const nchars = Math.max(2, String(maxN).length) + 1;
const nspaces = nchars - s.length - 1;
return prefix + ' '.repeat(nspaces) + s;
}
|
javascript
|
{
"resource": ""
}
|
q47417
|
list
|
train
|
function list(delta = 5) {
return selectedFrame.list(delta)
.then(null, (error) => {
print('You can\'t list source code right now');
throw error;
});
}
|
javascript
|
{
"resource": ""
}
|
q47418
|
getRequiredModuleName
|
train
|
function getRequiredModuleName(node) {
var moduleName;
// node has arguments and first argument is string
if (node.arguments.length && isString(node.arguments[0])) {
var argValue = path.basename(node.arguments[0].value.trim());
// check if value is in required modules array
if (requiredModules.indexOf(argValue) !== -1) {
moduleName = argValue;
}
}
return moduleName;
}
|
javascript
|
{
"resource": ""
}
|
q47419
|
intToBytes
|
train
|
function intToBytes(num) {
var bytes = [];
for(var i=7 ; i>=0 ; --i) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
}
|
javascript
|
{
"resource": ""
}
|
q47420
|
hexToBytes
|
train
|
function hexToBytes(hex) {
var bytes = [];
for(var c = 0, C = hex.length; c < C; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
}
|
javascript
|
{
"resource": ""
}
|
q47421
|
addInlined
|
train
|
function addInlined(tagName, lang) {
var includedCdataInside = {}
includedCdataInside['language-' + lang] = {
pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
lookbehind: true,
inside: Prism.languages[lang]
}
includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i
var inside = {
'included-cdata': {
pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
inside: includedCdataInside
}
}
inside['language-' + lang] = {
pattern: /[\s\S]+/,
inside: Prism.languages[lang]
}
var def = {}
def[tagName] = {
pattern: RegExp(
/(<__[\s\S]*?>)(?:<!\[CDATA\[[\s\S]*?\]\]>\s*|[\s\S])*?(?=<\/__>)/.source.replace(
/__/g,
tagName
),
'i'
),
lookbehind: true,
greedy: true,
inside: inside
}
Prism.languages.insertBefore('markup', 'cdata', def)
}
|
javascript
|
{
"resource": ""
}
|
q47422
|
train
|
function(env, language, placeholderPattern, replaceFilter) {
if (env.language !== language) {
return
}
var tokenStack = (env.tokenStack = [])
env.code = env.code.replace(placeholderPattern, function(match) {
if (typeof replaceFilter === 'function' && !replaceFilter(match)) {
return match
}
var i = tokenStack.length
var placeholder
// Check for existing strings
while (
env.code.indexOf((placeholder = getPlaceholder(language, i))) !==
-1
)
++i
// Create a sparse array
tokenStack[i] = match
return placeholder
})
// Switch the grammar to markup
env.grammar = Prism.languages.markup
}
|
javascript
|
{
"resource": ""
}
|
|
q47423
|
train
|
function(env, language) {
if (env.language !== language || !env.tokenStack) {
return
}
// Switch the grammar back
env.grammar = Prism.languages[language]
var j = 0
var keys = Object.keys(env.tokenStack)
function walkTokens(tokens) {
for (var i = 0; i < tokens.length; i++) {
// all placeholders are replaced already
if (j >= keys.length) {
break
}
var token = tokens[i]
if (
typeof token === 'string' ||
(token.content && typeof token.content === 'string')
) {
var k = keys[j]
var t = env.tokenStack[k]
var s = typeof token === 'string' ? token : token.content
var placeholder = getPlaceholder(language, k)
var index = s.indexOf(placeholder)
if (index > -1) {
++j
var before = s.substring(0, index)
var middle = new Prism.Token(
language,
Prism.tokenize(t, env.grammar),
'language-' + language,
t
)
var after = s.substring(index + placeholder.length)
var replacement = []
if (before) {
replacement.push.apply(replacement, walkTokens([before]))
}
replacement.push(middle)
if (after) {
replacement.push.apply(replacement, walkTokens([after]))
}
if (typeof token === 'string') {
tokens.splice.apply(tokens, [i, 1].concat(replacement))
} else {
token.content = replacement
}
}
} else if (
token.content /* && typeof token.content !== 'string' */
) {
walkTokens(token.content)
}
}
return tokens
}
walkTokens(env.tokens)
}
|
javascript
|
{
"resource": ""
}
|
|
q47424
|
WrappedTree
|
train
|
function WrappedTree(w, h, y, c = []) {
const me = this;
// size
me.w = w || 0;
me.h = h || 0;
// position
me.y = y || 0;
me.x = 0;
// children
me.c = c || [];
me.cs = c.length;
// modified
me.prelim = 0;
me.mod = 0;
me.shift = 0;
me.change = 0;
// left/right tree
me.tl = null;
me.tr = null;
// extreme left/right tree
me.el = null;
me.er = null;
// modified left/right tree
me.msel = 0;
me.mser = 0;
}
|
javascript
|
{
"resource": ""
}
|
q47425
|
sortedKeys
|
train
|
function sortedKeys(obj, orderedKeys) {
var keys = Object.keys(obj).sort();
var fresh = {};
orderedKeys.forEach(function (key) {
if (keys.indexOf(key) === -1) {
return;
}
fresh[key] = obj[key];
});
keys.forEach(function (key) {
if (orderedKeys.indexOf(key) !== -1) {
return;
}
fresh[key] = obj[key];
});
return fresh;
}
|
javascript
|
{
"resource": ""
}
|
q47426
|
bytes
|
train
|
function bytes(value, options) {
if (typeof value === 'string') {
return parse(value);
}
if (typeof value === 'number') {
return format(value, options);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q47427
|
format
|
train
|
function format(value, options) {
if (!Number.isFinite(value)) {
return null;
}
var mag = Math.abs(value);
var thousandsSeparator = (options && options.thousandsSeparator) || '';
var unitSeparator = (options && options.unitSeparator) || '';
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
var fixedDecimals = Boolean(options && options.fixedDecimals);
var unit = (options && options.unit) || '';
if (!unit || !map[unit.toLowerCase()]) {
if (mag >= map.pb) {
unit = 'PB';
} else if (mag >= map.tb) {
unit = 'TB';
} else if (mag >= map.gb) {
unit = 'GB';
} else if (mag >= map.mb) {
unit = 'MB';
} else if (mag >= map.kb) {
unit = 'KB';
} else {
unit = 'B';
}
}
var val = value / map[unit.toLowerCase()];
var str = val.toFixed(decimalPlaces);
if (!fixedDecimals) {
str = str.replace(formatDecimalsRegExp, '$1');
}
if (thousandsSeparator) {
str = str.replace(formatThousandsRegExp, thousandsSeparator);
}
return str + unitSeparator + unit;
}
|
javascript
|
{
"resource": ""
}
|
q47428
|
parse
|
train
|
function parse(val) {
if (typeof val === 'number' && !isNaN(val)) {
return val;
}
if (typeof val !== 'string') {
return null;
}
// Test if the string passed is valid
var results = parseRegExp.exec(val);
var floatValue;
var unit = 'b';
if (!results) {
// Nothing could be extracted from the given string
floatValue = parseInt(val, 10);
unit = 'b'
} else {
// Retrieve the value and the unit
floatValue = parseFloat(results[1]);
unit = results[4].toLowerCase();
}
return Math.floor(map[unit] * floatValue);
}
|
javascript
|
{
"resource": ""
}
|
q47429
|
traverseChild
|
train
|
function traverseChild(node, childNode, childspec, result) {
if (childNode.nodeType === 3 && /^\s+$/.test(childNode.nodeValue)) {
// Whitespace... nothing to do.
return;
}
var localName = (0, _camelize2['default'])(childNode.localName, '-');
if (!(localName in childspec)) {
debug('Unexpected node of type ' + localName + ' encountered while ' + 'parsing ' + node.localName + ' node!');
var value = childNode.textContent;
if (localName in result) {
if (!Array.isArray(result[localName])) {
// Since we've already encountered this node type and we haven't yet
// made an array for it, make an array now.
result[localName] = [result[localName]];
}
result[localName].push(value);
return;
}
// First time we're encountering this node.
result[localName] = value;
return;
}
var traversal = traverse[localName](childNode);
if (childspec[localName]) {
// Expect multiple.
result[localName].push(traversal);
} else {
// Expect single.
result[localName] = traversal;
}
}
|
javascript
|
{
"resource": ""
}
|
q47430
|
co
|
train
|
function co(gen) {
var ctx = this;
var args = slice.call(arguments, 1)
// we wrap everything in a promise to avoid promise chaining,
// which leads to memory leak errors.
// see https://github.com/tj/co/issues/180
return new Promise(function(resolve, reject) {
if (typeof gen === 'function') gen = gen.apply(ctx, args);
if (!gen || typeof gen.next !== 'function') return resolve(gen);
onFulfilled();
/**
* @param {Mixed} res
* @return {Promise}
* @api private
*/
function onFulfilled(res) {
var ret;
try {
ret = gen.next(res);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* @param {Error} err
* @return {Promise}
* @api private
*/
function onRejected(err) {
var ret;
try {
ret = gen.throw(err);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* Get the next value in the generator,
* return a promise.
*
* @param {Object} ret
* @return {Promise}
* @api private
*/
function next(ret) {
if (ret.done) return resolve(ret.value);
var value = toPromise.call(ctx, ret.value);
if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
+ 'but the following object was passed: "' + String(ret.value) + '"'));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47431
|
ucs2encode
|
train
|
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
|
javascript
|
{
"resource": ""
}
|
q47432
|
toUnicode
|
train
|
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
|
javascript
|
{
"resource": ""
}
|
q47433
|
toASCII
|
train
|
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
|
javascript
|
{
"resource": ""
}
|
q47434
|
ProgressBar
|
train
|
function ProgressBar(progress) {
// Make it 50 characters length
progress = Math.min(100, progress)
var units = Math.round(progress / 2)
return chalk.dim('[') + chalk.blue('=').repeat(units) + ' '.repeat(50 - units) + chalk.dim('] ') + chalk.yellow(progress + '%')
}
|
javascript
|
{
"resource": ""
}
|
q47435
|
InstalationProgress
|
train
|
function InstalationProgress(library, step, finished) {
var fillSpaces = ' '.repeat(15 - library.length)
if (finished) {
return chalk.cyan.dim(' > ') + chalk.yellow.dim(library) + fillSpaces + chalk.green('Installed')
} else {
return chalk.cyan(' > ') + chalk.yellow(library) + fillSpaces+ chalk.blue(step)
}
}
|
javascript
|
{
"resource": ""
}
|
q47436
|
negativeValues
|
train
|
function negativeValues(series) {
let i, j, data;
for (i = 0; i < series.length; i++) {
data = series[i].data;
for (j = 0; j < data.length; j++) {
if (data[j][1] < 0) {
return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q47437
|
copySeries
|
train
|
function copySeries(series) {
let newSeries = [], i, j;
for (i = 0; i < series.length; i++) {
let copy = {};
for (j in series[i]) {
if (series[i].hasOwnProperty(j)) {
copy[j] = series[i][j];
}
}
newSeries.push(copy);
}
return newSeries;
}
|
javascript
|
{
"resource": ""
}
|
q47438
|
eyesIt
|
train
|
function eyesIt(_it, _itArgs, config) {
const {
windowSize,
specVersion,
enableSnapshotAtBrowserGet,
enableSnapshotAtEnd,
} = merge({}, defaultConfig, config);
const spec = _it.apply(this, _itArgs);
const hooked = spec.beforeAndAfterFns;
spec.beforeAndAfterFns = function() {
//TODO: are we sure that we need to pass args (msg, itFn) to hooked?
const result = hooked.apply(this, _itArgs);
result.befores.unshift({
fn: function(done) {
_enableSnapshotAtBrowserGet = enableSnapshotAtBrowserGet;
eyes
.open(browser, appName, buildSpecName(spec, specVersion), windowSize)
.then(done);
},
timeout: () => 30000,
});
result.afters.unshift({
fn: function(done) {
_enableSnapshotAtBrowserGet = false;
Promise.resolve()
.then(() => {
if (enableSnapshotAtEnd) {
return eyes.checkWindow('end');
}
})
.then(done)
.catch(err => handleError(err, done));
},
timeout: () => 30000,
});
result.afters.push({
fn: function(done) {
eyes
.close()
.then(done)
.catch(err => handleError(err, done));
},
timeout: () => 30000,
});
return result;
};
return spec;
}
|
javascript
|
{
"resource": ""
}
|
q47439
|
findProvidesModule
|
train
|
function findProvidesModule(directories, opts = {}) {
const options = Object.assign({}, defaultOpts, opts);
const modulesMap = {};
const walk = dir => {
const stat = fs.lstatSync(dir);
if (stat.isDirectory()) {
fs.readdirSync(dir).forEach(file => {
if (options.blacklist.indexOf(file) >= 0) {
return;
}
walk(path.join(dir, file));
});
return;
}
if (stat.isFile()) {
const jsFileName = getJSFileName(dir);
if (!jsFileName) {
return;
}
const fileName = getPlatformFileName(jsFileName, options.platforms);
const moduleName = getProvidedModuleName(dir);
if (!moduleName) {
return;
}
// Throw when duplicated modules are provided from a different
// fileName
if (modulesMap[moduleName] && modulesMap[moduleName] !== fileName) {
throw new Error('Duplicate haste module found');
}
modulesMap[moduleName] = fileName;
}
};
directories.forEach(walk);
return modulesMap;
}
|
javascript
|
{
"resource": ""
}
|
q47440
|
reload
|
train
|
async function reload() {
const requestOptions = {
hostname: 'localhost',
port: 8081,
path: '/reloadapp',
method: 'HEAD',
};
const req = http.request(requestOptions, () => {
clear();
logger.done('Sent reload request');
req.end();
});
req.on('error', e => {
clear();
const error = e.toString();
if (error.includes('connect ECONNREFUSED')) {
logger.error(`Reload request failed. Make sure Haul is up.`);
} else {
logger.error(e);
}
});
req.end();
}
|
javascript
|
{
"resource": ""
}
|
q47441
|
extractClassName
|
train
|
function extractClassName(name) {
if (name.indexOf('(') === -1) {
return { entityName: name, tableName: _.snakeCase(name).toLowerCase() };
}
const split = name.split('(');
return {
entityName: split[0].trim(),
tableName: _.snakeCase(
split[1].slice(0, split[1].length - 1).trim()
).toLowerCase()
};
}
|
javascript
|
{
"resource": ""
}
|
q47442
|
getXmlElementFromRawIndexes
|
train
|
function getXmlElementFromRawIndexes(root, indexInfo) {
let parentPackage = root;
for (let j = 0; j < indexInfo.path.length; j++) {
parentPackage = parentPackage.packagedElement[indexInfo.path[j]];
}
return parentPackage.packagedElement[indexInfo.index];
}
|
javascript
|
{
"resource": ""
}
|
q47443
|
generateEntities
|
train
|
function generateEntities(entityIdsToGenerate, classes, entityNamesToGenerate, options) {
if (shouldEntitiesBeGenerated(entityIdsToGenerate, entityNamesToGenerate, classes)) {
winston.info('No entity has to be generated.');
return;
}
displayEntitiesToGenerate(entityIdsToGenerate, entityNamesToGenerate, classes);
entityIdsToGenerate.forEach((entityToGenerate, index) => {
if (entityNamesToGenerate.includes(classes[entityToGenerate].name)) {
const commandWrapper = createAndInitCommandBuilder(
classes[entityToGenerate].name,
options,
index !== entityIdsToGenerate.length - 1
);
childProcess.spawnSync(
commandWrapper.command,
commandWrapper.args,
{ stdio: commandWrapper.stdio }
);
winston.info('\n');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47444
|
checkValidityOfAssociation
|
train
|
function checkValidityOfAssociation(association, sourceName, destinationName) {
if (!association || !association.type) {
throw new BuildException(
exceptions.NullPointer, 'The association must not be nil.');
}
switch (association.type) {
case cardinalities.ONE_TO_ONE:
checkOneToOne(association, sourceName, destinationName);
break;
case cardinalities.ONE_TO_MANY:
checkOneToMany(association, sourceName, destinationName);
break;
case cardinalities.MANY_TO_ONE:
checkManyToOne(association, sourceName, destinationName);
break;
case cardinalities.MANY_TO_MANY:
checkManyToMany(association, sourceName, destinationName);
break;
default:
throw new BuildException(
exceptions.WrongAssociation,
`The association type ${association.type} isn't supported.`);
}
}
|
javascript
|
{
"resource": ""
}
|
q47445
|
getClassNames
|
train
|
function getClassNames(classes) {
if (!classes) {
throw new BuildException(
exceptions.NullPointer, 'The classes object cannot be nil.');
}
const object = {};
Object.keys(classes).forEach((classId) => {
object[classId] = classes[classId].name;
});
return object;
}
|
javascript
|
{
"resource": ""
}
|
q47446
|
detect
|
train
|
function detect(root) {
if (!root) {
throw new BuildException(
exceptions.NullPointer, 'The root element can not be null.');
}
if (root.eAnnotations && root.eAnnotations[0].$.source === 'Objing') {
winston.info('Parser detected: MODELIO.\n');
return modelio;
} else if (root.eAnnotations
&& root.eAnnotations[0].$.source === 'genmymodel') {
winston.info('Parser detected: GENMYMODEL.\n');
return genmymodel;
}
if (UndetectedEditors.length === 0) {
// this should not be happening
throw new BuildException(exceptions.UndetectedEditor,
'Your editor has not been detected, and this should not be happening.'
+ '\nPlease report this issue by mentioning what your editor is.');
}
return askForEditor();
}
|
javascript
|
{
"resource": ""
}
|
q47447
|
askConfirmation
|
train
|
function askConfirmation(args) {
let userAnswer = 'no-answer';
const merged = merge(DEFAULTS.CONFIRMATIONS, args);
inquirer.prompt([
{
type: DEFAULTS.QUESTION_TYPES.CONFIRM,
name: 'choice',
message: merged.question,
default: merged.defaultValue
}
]).then((answer) => {
userAnswer = answer.choice;
});
while (userAnswer === 'no-answer') {
wait(100);
}
return userAnswer;
}
|
javascript
|
{
"resource": ""
}
|
q47448
|
selectMultipleChoices
|
train
|
function selectMultipleChoices(args) {
args.choices = args.choices || prepareChoices(args.classes);
let result = null;
const merged = merge(DEFAULTS.MULTIPLE_CHOICES, args);
inquirer.prompt([
{
type: DEFAULTS.QUESTION_TYPES.CHECKBOX,
name: 'answer',
message: merged.question,
choices: merged.choices,
filter: merged.filterFunction
}
]).then((answers) => {
if (answers.answer.length === 0) {
result = DEFAULTS.NOTHING;
} else {
result = answers.answer;
}
});
while (!result) {
wait(100);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47449
|
toJDL
|
train
|
function toJDL(parsedData, options) {
assertParsedDataIsValid(parsedData);
const jdlObject = new JDLObject();
const jdlEnumArray = convertEnums(parsedData.enums);
addEnumsToJDLObject(jdlObject, jdlEnumArray);
const jdlEntityObject = convertClasses(parsedData);
addEntitiesToJDLObject(jdlObject, jdlEntityObject);
const jdlRelationshipArray = convertAssociations(parsedData, jdlObject.entities);
addRelationshipsToJDLObject(jdlObject, jdlRelationshipArray);
if (options) {
const jdlOptionArray = convertOptions(options, parsedData.classNames.length);
addOptionsToJDLObject(jdlObject, jdlOptionArray);
}
return jdlObject;
}
|
javascript
|
{
"resource": ""
}
|
q47450
|
createParser
|
train
|
function createParser(args) {
if (!args || !args.file || !args.databaseType) {
throw new BuildException(
exceptions.IllegalArgument,
'The file and the database type must be passed');
}
const types = initDatabaseTypeHolder(args.databaseType);
if (args.editor) {
const root = getRootElement(readFileContent(args.file));
return getFileParserByEditor(args.editor, root, types, args.noUserManagement);
}
return getParserForSingleFile(args.file, types, args.noUserManagement);
}
|
javascript
|
{
"resource": ""
}
|
q47451
|
checkForReservedClassName
|
train
|
function checkForReservedClassName(args) {
if (!args) {
return;
}
if (JHipsterCore.isReservedClassName(args.name)) {
if (args.shouldThrow) {
throw new BuildException(
exceptions.IllegalName,
`The passed class name '${args.name}' is reserved.`);
} else {
winston.warn(
chalk.yellow(
`The passed class name '${args.name}' is reserved .`));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47452
|
checkForReservedTableName
|
train
|
function checkForReservedTableName(args) {
if (!args) {
return;
}
if (args.databaseTypeName) {
checkTableName(args.name, args.databaseTypeName, args.shouldThrow);
} else {
for (let i = 0, types = Object.keys(DatabaseTypes); i < types.length; i++) {
if (typeof DatabaseTypes[types[i]] !== 'function') {
checkTableName(args.name, DatabaseTypes[types[i]], args.shouldThrow);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47453
|
checkForReservedFieldName
|
train
|
function checkForReservedFieldName(args) {
if (!args) {
return;
}
if (args.databaseTypeName) {
checkFieldName(args.name, args.databaseTypeName, args.shouldThrow);
} else {
for (let i = 0, types = Object.keys(DatabaseTypes); i < types.length; i++) {
checkFieldName(args.name, DatabaseTypes[types[i]], args.shouldThrow);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47454
|
train
|
function(){
if(this.$phase === 'digest' || this._mute) return;
this.$phase = 'digest';
var dirty = false, n =0;
while(dirty = this._digest()){
if((++n) > 20){ // max loop
throw Error('there may a circular dependencies reaches')
}
}
// stable watch is dirty
var stableDirty = this._digest(true);
if( (n > 0 || stableDirty) && this.$emit) {
this.$emit("$update");
if (this.devtools) {
this.devtools.emit("flush", this)
}
}
this.$phase = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q47455
|
train
|
function(stable){
if(this._mute) return;
var watchers = !stable? this._watchers: this._watchersForStable;
var dirty = false, children, watcher, watcherDirty;
var len = watchers && watchers.length;
if(len){
var mark = 0, needRemoved=0;
for(var i =0; i < len; i++ ){
watcher = watchers[i];
var shouldRemove = !watcher || watcher.removed;
if( shouldRemove ){
needRemoved += 1;
}else{
watcherDirty = this._checkSingleWatch(watcher);
if(watcherDirty) dirty = true;
}
// remove when encounter first unmoved item or touch the end
if( !shouldRemove || i === len-1 ){
if( needRemoved ){
watchers.splice(mark, needRemoved );
len -= needRemoved;
i -= needRemoved;
needRemoved = 0;
}
mark = i+1;
}
}
}
// check children's dirty.
children = this._children;
if(children && children.length){
for(var m = 0, mlen = children.length; m < mlen; m++){
var child = children[m];
if(child && child._digest(stable)) dirty = true;
}
}
return dirty;
}
|
javascript
|
{
"resource": ""
}
|
|
q47456
|
train
|
function(watcher){
var dirty = false;
if(!watcher) return;
var now, last, tlast, tnow,
eq, diff, keyOf, trackDiff
if(!watcher.test){
now = watcher.get(this);
last = watcher.last;
keyOf = watcher.keyOf
if(now !== last || watcher.force){
tlast = _.typeOf(last);
tnow = _.typeOf(now);
eq = true;
// !Object
if( !(tnow === 'object' && tlast==='object' && watcher.deep) ){
// Array
if( tnow === 'array' && ( tlast=='undefined' || tlast === 'array') ){
if(typeof keyOf === 'function'){
trackDiff = diffTrack(now, watcher.last || [], keyOf )
diff = trackDiff.steps;
if(trackDiff.dirty) dirty = true;
}else{
diff = diffArray(now, watcher.last || [], watcher.diff)
}
if(!dirty && (tlast !== 'array' || diff === true || diff.length) ) dirty = true;
}else{
eq = _.equals( now, last );
if( !eq || watcher.force ){
watcher.force = null;
dirty = true;
}
}
}else{
diff = diffObject( now, last, watcher.diff, keyOf );
if(diff.isTrack){
trackDiff = diff;
diff = trackDiff.steps;
}
if( diff === true || diff.length ) dirty = true;
}
}
} else{
// @TODO 是否把多重改掉
var result = watcher.test(this);
if(result){
dirty = true;
watcher.fn.apply(this, result)
}
}
if(dirty && !watcher.test){
if(tnow === 'object' && watcher.deep || tnow === 'array'){
watcher.last = _.clone(now);
}else{
watcher.last = now;
}
watcher.fn.call(this, now, last, diff, trackDiff && trackDiff.oldKeyMap, trackDiff && trackDiff.dirty)
if(watcher.once) this.$unwatch(watcher)
}
return dirty;
}
|
javascript
|
{
"resource": ""
}
|
|
q47457
|
train
|
function(item){
var children,node, nodes;
if(!item) return;
if(typeof item.node === "function") return item.node();
if(typeof item.nodeType === "number") return item;
if(item.group) return combine.node(item.group)
item = item.children || item;
if( Array.isArray(item )){
var len = item.length;
if(len === 1){
return combine.node(item[0]);
}
nodes = [];
for(var i = 0, len = item.length; i < len; i++ ){
node = combine.node(item[i]);
if(Array.isArray(node)){
for (var j = 0, len1 = node.length; j < len1; j++){
nodes.push(node[j])
}
}else if(node) {
nodes.push(node)
}
}
return nodes;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47458
|
ld
|
train
|
function ld(array1, array2, equalFn){
var n = array1.length;
var m = array2.length;
var equalFn = equalFn || equals;
var matrix = [];
for(var i = 0; i <= n; i++){
matrix.push([i]);
}
for(var j=1;j<=m;j++){
matrix[0][j]=j;
}
for(var i = 1; i <= n; i++){
for(var j = 1; j <= m; j++){
if(equalFn(array1[i-1], array2[j-1])){
matrix[i][j] = matrix[i-1][j-1];
}else{
matrix[i][j] = Math.min(
matrix[i-1][j]+1, //delete
matrix[i][j-1]+1//add
)
}
}
}
return matrix;
}
|
javascript
|
{
"resource": ""
}
|
q47459
|
diffArray
|
train
|
function diffArray(arr2, arr1, diff, diffFn) {
if(!diff) return _.simpleDiff(arr2, arr1);
var matrix = ld(arr1, arr2, diffFn)
var n = arr1.length;
var i = n;
var m = arr2.length;
var j = m;
var edits = [];
var current = matrix[i][j];
while(i>0 || j>0){
// the last line
if (i === 0) {
edits.unshift(3);
j--;
continue;
}
// the last col
if (j === 0) {
edits.unshift(2);
i--;
continue;
}
var northWest = matrix[i - 1][j - 1];
var west = matrix[i - 1][j];
var north = matrix[i][j - 1];
var min = Math.min(north, west, northWest);
if (min === west) {
edits.unshift(2); //delete
i--;
current = west;
} else if (min === northWest ) {
if (northWest === current) {
edits.unshift(0); //no change
} else {
edits.unshift(1); //update
current = northWest;
}
i--;
j--;
} else {
edits.unshift(3); //add
j--;
current = north;
}
}
var LEAVE = 0;
var ADD = 3;
var DELELE = 2;
var UPDATE = 1;
var n = 0;m=0;
var steps = [];
var step = { index: null, add:0, removed:[] };
for(var i=0;i<edits.length;i++){
if(edits[i] > 0 ){ // NOT LEAVE
if(step.index === null){
step.index = m;
}
} else { //LEAVE
if(step.index != null){
steps.push(step)
step = {index: null, add:0, removed:[]};
}
}
switch(edits[i]){
case LEAVE:
n++;
m++;
break;
case ADD:
step.add++;
m++;
break;
case DELELE:
step.removed.push(arr1[n])
n++;
break;
case UPDATE:
step.add++;
step.removed.push(arr1[n])
n++;
m++;
break;
}
}
if(step.index != null){
steps.push(step)
}
return steps
}
|
javascript
|
{
"resource": ""
}
|
q47460
|
wrapSet
|
train
|
function wrapSet(set){
return function(context, value){
set.call( context, value, context.data );
return value;
}
}
|
javascript
|
{
"resource": ""
}
|
q47461
|
createFSM
|
train
|
function createFSM() {
return {
_stack: [],
enter: function(state) {
this._stack.push(state);
return this;
},
leave: function(state) {
var stack = this._stack;
// if state is falsy or state equals to last item in stack
if(!state || stack[stack.length-1] === state) {
stack.pop();
}
return this;
},
get: function() {
var stack = this._stack;
return stack[stack.length - 1];
},
all: function() {
return this._stack;
},
is: function(state) {
var stack = this._stack;
return stack[stack.length - 1] === state
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47462
|
train
|
function(definition, options){
var prevRunning = env.isRunning;
env.isRunning = true;
var node, template, cursor, context = this, body, mountNode;
options = options || {};
definition = definition || {};
var dtemplate = definition.template;
if(env.browser) {
if( node = tryGetSelector( dtemplate ) ){
dtemplate = node;
}
if( dtemplate && dtemplate.nodeType ){
definition.template = dtemplate.innerHTML
}
mountNode = definition.mountNode;
if(typeof mountNode === 'string'){
mountNode = dom.find( mountNode );
if(!mountNode) throw Error('mountNode ' + mountNode + ' is not found')
}
if(mountNode){
cursor = nodeCursor(mountNode.firstChild, mountNode)
delete definition.mountNode
}else{
cursor = options.cursor
}
}
template = shared.initDefinition(context, definition)
if(context.$parent){
context.$parent._append(context);
}
context._children = [];
context.$refs = {};
context.$root = context.$root || context;
var extra = options.extra;
var oldModify = extra && extra.$$modify;
var newExtra;
if( body = context._body ){
context._body = null
var modifyBodyComponent = context.modifyBodyComponent;
if( typeof modifyBodyComponent === 'function'){
modifyBodyComponent = modifyBodyComponent.bind(this)
newExtra = _.createObject(extra);
newExtra.$$modify = function( comp ){
return modifyBodyComponent(comp, oldModify? oldModify: NOOP)
}
}else{ //@FIXIT: multiply modifier
newExtra = extra
}
if(body.ast && body.ast.length){
context.$body = _.getCompileFn(body.ast, body.ctx , {
outer: context,
namespace: options.namespace,
extra: newExtra,
record: true
})
}
}
// handle computed
if(template){
var cplOpt = {
namespace: options.namespace,
cursor: cursor
}
// if(extra && extra.$$modify){
cplOpt.extra = {$$modify : extra&& extra.$$modify}
// }
context.group = context.$compile(template, cplOpt);
combine.node(context);
}
// modify在compile之后调用, 这样就无需处理SSR相关逻辑
if( oldModify ){
oldModify(this);
}
// this is outest component
if( !context.$parent ) context.$update();
context.$ready = true;
context.$emit("$init");
if( context.init ) context.init( context.data );
context.$emit("$afterInit");
env.isRunning = prevRunning;
// children is not required;
if (this.devtools) {
this.devtools.emit("init", this)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47463
|
train
|
function(name, cfg){
if(!name) return;
var type = typeof name;
if(type === 'object' && !cfg){
for(var k in name){
if(name.hasOwnProperty(k)) this.directive(k, name[k]);
}
return this;
}
var directives = this._directives, directive;
if(cfg == null){
if( type === 'string' ){
if( directive = directives[name] ) return directive;
else{
var regexp = directives.__regexp__;
for(var i = 0, len = regexp.length; i < len ; i++){
directive = regexp[i];
var test = directive.regexp.test(name);
if(test) return directive;
}
}
}
}else{
if( typeof cfg === 'function') cfg = { link: cfg }
if( type === 'string' ) directives[name] = cfg;
else{
cfg.regexp = name;
directives.__regexp__.push(cfg)
}
if(typeof cfg.link !== 'function') cfg.link = NOOP;
return this
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47464
|
train
|
function(name, value){
var needGenLexer = false;
if(typeof name === "object"){
for(var i in name){
// if you config
if( i ==="END" || i==='BEGIN' ) needGenLexer = true;
config[i] = name[i];
}
}
if(needGenLexer) Lexer.setup();
}
|
javascript
|
{
"resource": ""
}
|
|
q47465
|
train
|
function(ast, options){
options = options || {};
if(typeof ast === 'string'){
ast = new Parser(ast).parse()
}
var preExt = this.__ext__,
record = options.record,
records;
if(options.extra) this.__ext__ = options.extra;
if(record) this._record();
var group = this._walk(ast, options);
if(record){
records = this._release();
var self = this;
if( records.length ){
// auto destroy all wather;
group.ondestroy = function(){ self.$unwatch(records); }
}
}
if(options.extra) this.__ext__ = preExt;
return group;
}
|
javascript
|
{
"resource": ""
}
|
|
q47466
|
train
|
function(component, expr1, expr2){
var self = this;
// basic binding
if(!component || !(component instanceof Regular)) throw "$bind() should pass Regular component as first argument";
if(!expr1) throw "$bind() should pass as least one expression to bind";
if(!expr2) expr2 = expr1;
expr1 = parse.expression( expr1 );
expr2 = parse.expression( expr2 );
// set is need to operate setting ;
if(expr2.set){
var wid1 = this.$watch( expr1, function(value){
component.$update(expr2, value)
});
component.$on('$destroy', function(){
self.$unwatch(wid1)
})
}
if(expr1.set){
var wid2 = component.$watch(expr2, function(value){
self.$update(expr1, value)
});
// when brother destroy, we unlink this watcher
this.$on('$destroy', component.$unwatch.bind(component,wid2))
}
// sync the component's state to called's state
expr2.set(component, expr1.get(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q47467
|
train
|
function(path, parent, defaults, ext){
if( path === undefined ) return undefined;
if(ext && typeof ext === 'object'){
if(ext[path] !== undefined) return ext[path];
}
// reject to get from computed, return undefined directly
// like { empty.prop }, empty equals undefined
// prop shouldn't get from computed
if(parent === null) {
return undefined
}
if(parent && typeof parent[path] !== 'undefined') {
return parent[path]
}
// without parent, get from computed
if (parent !== null) {
var computed = this.computed,
computedProperty = computed[path];
if(computedProperty){
if(computedProperty.type==='expression' && !computedProperty.get) this._touchExpr(computedProperty);
if(computedProperty.get) return computedProperty.get(this);
else _.log("the computed '" + path + "' don't define the get function, get data."+path + " altnately", "warn")
}
}
if( defaults === undefined ){
return undefined;
}
return defaults[path];
}
|
javascript
|
{
"resource": ""
}
|
|
q47468
|
train
|
function(path, value, data , op, computed){
var computed = this.computed,
op = op || "=", prev,
computedProperty = computed? computed[path]:null;
if(op !== '='){
prev = computedProperty? computedProperty.get(this): data[path];
switch(op){
case "+=":
value = prev + value;
break;
case "-=":
value = prev - value;
break;
case "*=":
value = prev * value;
break;
case "/=":
value = prev / value;
break;
case "%=":
value = prev % value;
break;
}
}
if(computedProperty) {
if(computedProperty.set) return computedProperty.set(this, value);
}
data[path] = value;
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q47469
|
updateSimple
|
train
|
function updateSimple(newList, oldList, rawNewValue ){
var nlen = newList.length;
var olen = oldList.length;
var mlen = Math.min(nlen, olen);
updateRange(0, mlen, newList, rawNewValue)
if(nlen < olen){ //need add
removeRange(nlen, olen-nlen, children);
}else if(nlen > olen){
addRange(olen, nlen, newList, rawNewValue);
}
}
|
javascript
|
{
"resource": ""
}
|
q47470
|
initText
|
train
|
function initText(elem, parsed, extra){
var param = extra.param;
var throttle, lazy = param.lazy
if('throttle' in param){
// <input throttle r-model>
if(param.throttle === true){
throttle = 400;
}else{
throttle = parseInt(param.throttle, 10)
}
}
var self = this;
var wc = this.$watch(parsed, function(newValue){
if(elem.value !== newValue) elem.value = newValue == null? "": "" + newValue;
}, STABLE);
// @TODO to fixed event
var isCompositing = false;
var handler = function (ev){
if(isCompositing) return;
isCompositing = false;
var that = this;
if(ev.type==='cut' || ev.type==='paste'){
_.nextTick(function(){
var value = that.value
parsed.set(self, value);
wc.last = value;
self.$update();
})
}else{
var value = that.value
parsed.set(self, value);
wc.last = value;
self.$update();
}
};
function onCompositionStart(){
isCompositing = true;
}
function onCompositionEnd(ev){
isCompositing = false;
handler.call(this,ev)
}
if(throttle && !lazy){
var preHandle = handler, tid;
handler = _.throttle(handler, throttle);
}
if(hasInput === undefined){
hasInput = dom.msie !== 9 && "oninput" in document.createElement('input')
}
if(lazy){
dom.on(elem, 'change', handler)
}else{
if(typeof CompositionEvent === 'function' ){ //lazy的情况不需要compositionend
elem.addEventListener("compositionstart", onCompositionStart );
elem.addEventListener("compositionend", onCompositionEnd );
}
if( hasInput){
elem.addEventListener("input", handler );
}else{
dom.on(elem, "paste keyup cut change", handler)
}
}
if(parsed.get(self) === undefined && elem.value){
parsed.set(self, elem.value);
}
return function (){
if(lazy) return dom.off(elem, "change", handler);
if( hasInput ){
elem.removeEventListener("input", handler );
}else{
dom.off(elem, "paste keyup cut change", handler)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47471
|
mapResponse
|
train
|
function mapResponse(response) {
response.body = response.text;
response.statusCode = response.status;
return response;
}
|
javascript
|
{
"resource": ""
}
|
q47472
|
getScrollTop
|
train
|
function getScrollTop() {
// vue-jest ignore
if (!document) return;
if (document.scrollingElement) {
return document.scrollingElement.scrollTop;
}
if (document.body || window.pageXOffset) {
return document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset;
}
}
|
javascript
|
{
"resource": ""
}
|
q47473
|
discoverGateway
|
train
|
function discoverGateway(timeout = 10000) {
const mdns = createMDNSServer({
reuseAddr: true,
loopback: false,
noInit: true,
});
let timer;
const domain = "_coap._udp.local";
return new Promise((resolve, reject) => {
mdns.on("response", (resp) => {
const allAnswers = [...resp.answers, ...resp.additionals];
const discard = allAnswers.find(a => a.name === domain) == null;
if (discard)
return;
// ensure all record types were received
const ptrRecord = allAnswers.find(a => a.type === "PTR");
if (!ptrRecord)
return;
const srvRecord = allAnswers.find(a => a.type === "SRV");
if (!srvRecord)
return;
const txtRecord = allAnswers.find(a => a.type === "TXT");
if (!txtRecord)
return;
const aRecords = allAnswers.filter(a => a.type === "A" || a.type === "AAAA");
if (aRecords.length === 0)
return;
// extract the data
const match = /^gw\-[0-9a-f]{12}/.exec(ptrRecord.data);
const name = !!match ? match[0] : "unknown";
const host = srvRecord.data.target;
const { version } = parseTXTRecord(txtRecord.data);
const addresses = aRecords.map(a => a.data);
clearTimeout(timer);
mdns.destroy();
resolve({
name, host, version, addresses,
});
});
mdns.on("ready", () => {
mdns.query([
{ name: domain, type: "A" },
{ name: domain, type: "AAAA" },
{ name: domain, type: "PTR" },
{ name: domain, type: "SRV" },
{ name: domain, type: "TXT" },
]);
});
mdns.on("error", reject);
mdns.initServer();
if (typeof timeout === "number" && timeout > 0) {
timer = setTimeout(() => {
mdns.destroy();
resolve(null);
}, timeout);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47474
|
buildPropertyTransform
|
train
|
function buildPropertyTransform(kernel, options = {}) {
if (options.splitArrays == null)
options.splitArrays = true;
if (options.neverSkip == null)
options.neverSkip = false;
const ret = kernel;
ret.splitArrays = options.splitArrays;
ret.neverSkip = options.neverSkip;
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q47475
|
lookupKeyOrProperty
|
train
|
function lookupKeyOrProperty(target, keyOrProperty /*| keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_ipsoKey, constr);
return metadata && metadata[keyOrProperty];
}
|
javascript
|
{
"resource": ""
}
|
q47476
|
isRequired
|
train
|
function isRequired(target, reference, property) {
// get the class constructor
const constr = target.constructor;
logger_1.log(`${constr.name}: checking if ${property} is required...`, "silly");
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_required, constr) || {};
if (metadata.hasOwnProperty(property)) {
const ret = metadata[property];
if (typeof ret === "boolean")
return ret;
return ret(target, reference);
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q47477
|
serializeWith
|
train
|
function serializeWith(kernel, options) {
const transform = buildPropertyTransform(kernel, options);
return (target, property) => {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_serializeWith, constr) || {};
metadata[property] = transform;
// store back to the object
Reflect.defineMetadata(METADATA_serializeWith, metadata, constr);
};
}
|
javascript
|
{
"resource": ""
}
|
q47478
|
getSerializer
|
train
|
function getSerializer(target, property /* | keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_serializeWith, constr) || {};
if (metadata.hasOwnProperty(property))
return metadata[property];
// If there's no custom serializer, try to find a default one
const type = getPropertyType(target, property);
if (type && type.name in defaultSerializers) {
return defaultSerializers[type.name];
}
}
|
javascript
|
{
"resource": ""
}
|
q47479
|
deserializeWith
|
train
|
function deserializeWith(kernel, options) {
const transform = buildPropertyTransform(kernel, options);
return (target, property) => {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_deserializeWith, constr) || {};
metadata[property] = transform;
// store back to the object
Reflect.defineMetadata(METADATA_deserializeWith, metadata, constr);
};
}
|
javascript
|
{
"resource": ""
}
|
q47480
|
isSerializable
|
train
|
function isSerializable(target, property) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_doNotSerialize, constr) || {};
// if doNotSerialize is defined, don't serialize!
return !metadata.hasOwnProperty(property);
}
|
javascript
|
{
"resource": ""
}
|
q47481
|
getDeserializer
|
train
|
function getDeserializer(target, property /*| keyof T*/) {
// get the class constructor
const constr = target.constructor;
// retrieve the current metadata
const metadata = Reflect.getMetadata(METADATA_deserializeWith, constr) || {};
if (metadata.hasOwnProperty(property)) {
return metadata[property];
}
// If there's no custom deserializer, try to find a default one
const type = getPropertyType(target, property);
if (type && type.name in defaultDeserializers) {
return defaultDeserializers[type.name];
}
}
|
javascript
|
{
"resource": ""
}
|
q47482
|
parseNotificationDetails
|
train
|
function parseNotificationDetails(kvpList) {
const ret = {};
for (const kvp of kvpList) {
const parts = kvp.split("=");
ret[parts[0]] = parts[1];
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q47483
|
normalizeResourcePath
|
train
|
function normalizeResourcePath(path) {
path = path || "";
while (path.startsWith("/"))
path = path.slice(1);
while (path.endsWith("/"))
path = path.slice(0, -1);
return path;
}
|
javascript
|
{
"resource": ""
}
|
q47484
|
createRGBProxy
|
train
|
function createRGBProxy(raw = false) {
function get(me, key) {
switch (key) {
case "color": {
if (typeof me.color === "string" && rgbRegex.test(me.color)) {
// predefined color, return it
return me.color;
}
else {
// calculate it from hue/saturation
const { r, g, b } = conversions_1.conversions.rgbFromHSV(me.hue, me.saturation / 100, 1);
return conversions_1.conversions.rgbToString(r, g, b);
}
}
default: return me[key];
}
}
function set(me, key, value) {
switch (key) {
case "color": {
if (predefined_colors_1.predefinedColors.has(value)) {
// its a predefined color, use the predefined values
const definition = predefined_colors_1.predefinedColors.get(value); // we checked with `has`
if (raw) {
me.hue = definition.hue_raw;
me.saturation = definition.saturation_raw;
}
else {
me.hue = definition.hue;
me.saturation = definition.saturation;
}
}
else {
// only accept HEX colors
if (rgbRegex.test(value)) {
// calculate the X/Y values
const { r, g, b } = conversions_1.conversions.rgbFromString(value);
const { h, s /* ignore v */ } = conversions_1.conversions.rgbToHSV(r, g, b);
if (raw) {
me.hue = Math.round(h / 360 * predefined_colors_1.MAX_COLOR);
me.saturation = Math.round(s * predefined_colors_1.MAX_COLOR);
}
else {
me.hue = h;
me.saturation = s * 100;
}
}
}
break;
}
default: me[key] = value;
}
return true;
}
return { get, set };
}
|
javascript
|
{
"resource": ""
}
|
q47485
|
setHashOrThrowError
|
train
|
function setHashOrThrowError(parseMap, routeObject) {
var route = routeObject.route;
var get = routeObject.get;
var set = routeObject.set;
var call = routeObject.call;
getHashesFromRoute(route).
map(function mapHashToString(hash) { return hash.join(','); }).
forEach(function forEachRouteHash(hash) {
if (get && parseMap[hash + 'get'] ||
set && parseMap[hash + 'set'] ||
call && parseMap[hash + 'call']) {
throw new Error(errors.routeWithSamePrecedence + ' ' +
prettifyRoute(route));
}
if (get) {
parseMap[hash + 'get'] = true;
}
if (set) {
parseMap[hash + 'set'] = true;
}
if (call) {
parseMap[hash + 'call'] = true;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47486
|
decendTreeByRoutedToken
|
train
|
function decendTreeByRoutedToken(node, value, routeToken) {
var next = null;
switch (value) {
case Keys.keys:
case Keys.integers:
case Keys.ranges:
next = node[value];
if (!next) {
next = node[value] = {};
}
break;
default:
break;
}
if (next && routeToken) {
// matches the naming information on the node.
next[Keys.named] = routeToken.named;
next[Keys.name] = routeToken.name;
}
return next;
}
|
javascript
|
{
"resource": ""
}
|
q47487
|
getHashesFromRoute
|
train
|
function getHashesFromRoute(route, depth, hashes, hash) {
/*eslint-disable no-func-assign, no-param-reassign*/
depth = depth || 0;
hashes = hashes || [];
hash = hash || [];
/*eslint-enable no-func-assign, no-param-reassign*/
var routeValue = route[depth];
var isArray = Array.isArray(routeValue);
var length = isArray && routeValue.length || 0;
var idx = 0;
var value;
if (typeof routeValue === 'object' && !isArray) {
value = routeValue.type;
}
else if (!isArray) {
value = routeValue;
}
do {
if (isArray) {
value = routeValue[idx];
}
if (value === Keys.integers || value === Keys.ranges) {
hash[depth] = '__I__';
}
else if (value === Keys.keys) {
hash[depth] ='__K__';
}
else {
hash[depth] = value;
}
// recurse down the routed token
if (depth + 1 !== route.length) {
getHashesFromRoute(route, depth + 1, hashes, hash);
}
// Or just add it to hashes
else {
hashes.push(cloneArray(hash));
}
} while (isArray && ++idx < length);
return hashes;
}
|
javascript
|
{
"resource": ""
}
|
q47488
|
createNamedVariables
|
train
|
function createNamedVariables(route, action) {
return function innerCreateNamedVariables(matchedPath) {
var convertedArguments;
var len = -1;
var restOfArgs = slice(arguments, 1);
var isJSONObject = !isArray(matchedPath);
// A set uses a json object
if (isJSONObject) {
restOfArgs = [];
convertedArguments = matchedPath;
}
// Could be an array of pathValues for a set operation.
else if (isPathValue(matchedPath[0])) {
convertedArguments = [];
matchedPath.forEach(function(pV) {
pV.path = convertPathToRoute(pV.path, route);
convertedArguments[++len] = pV;
});
}
// else just convert and assign
else {
convertedArguments =
convertPathToRoute(matchedPath, route);
}
return action.apply(this, [convertedArguments].concat(restOfArgs));
};
}
|
javascript
|
{
"resource": ""
}
|
q47489
|
train
|
function(isInit) {
var containerWidth = self.$map.width();
if (self.paper.width !== containerWidth) {
var newScale = containerWidth / self.mapConf.width;
// Set new size
self.paper.setSize(containerWidth, self.mapConf.height * newScale);
// Create plots legend again to take into account the new scale
// Do not do this on init (it will be done later)
if (isInit !== true && self.options.legend.redrawOnResize) {
self.createLegends("plot", self.plots, newScale);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47490
|
train
|
function (elem) {
// Starts with hidden elements
elem.mapElem.attr({opacity: 0});
if (elem.textElem) elem.textElem.attr({opacity: 0});
// Set final element opacity
self.setElementOpacity(
elem,
(elem.mapElem.originalAttrs.opacity !== undefined) ? elem.mapElem.originalAttrs.opacity : 1,
animDuration
);
}
|
javascript
|
{
"resource": ""
}
|
|
q47491
|
pipe
|
train
|
function pipe(commands, input) {
if (!commands) {
return input;
}
return commands.reduce(function(input, cmd) {
return npmRun.sync(cmd, {
input: input
});
}, input);
}
|
javascript
|
{
"resource": ""
}
|
q47492
|
logError
|
train
|
function logError(e) {
var msg = typeof e === 'string' ? e : e.message;
// esprima.parse errors are in the format 'Line 123: Unexpected token &'
// we support both formats since users might replace the parser
if ((/Line \d+:/).test(msg)) {
// convert into "Error: <filepath>:<line> <error_message>"
msg = 'Error: ' + msg.replace(/[^\d]+(\d+): (.+)/, e.file + ':$1 $2');
} else {
// babylon.parse errors are in the format 'Unexpected token (0:4)'
var m = (/^([^\(]+)\s\((\d+):(\d+)\)/).exec(msg);
if (m) {
// convert into "Error: <filepath>:<line>:<char> <error_message>"
msg = 'Error: ' + e.file + ':' + m[2] + ':' + m[3] + ' ' + m[1];
} else if (msg.indexOf('Error:') < 0) {
msg = 'Error: ' + (e.file ? e.file + ' ' : '') + msg;
}
}
// set the error flag to true to use an exit code !== 0
exports.exitCode = 1;
// we don't call console.error directly to make it possible to mock during
// unit tests
exports.stderr.write(msg + '\n');
if (e.stack) {
exports.stderr.write(e.stack + '\n');
}
}
|
javascript
|
{
"resource": ""
}
|
q47493
|
recess
|
train
|
function recess(init, path, err) {
if (path = paths.shift()) {
return instances.push(new RECESS(path, options, recess))
}
// map/filter for errors
err = instances
.map(function (i) {
return i.errors.length && i.errors
})
.filter(function (i) {
return i
})
// if no error, set explicitly to null
err = err.length ? err[0] : null
//callback
callback && callback(err, instances)
}
|
javascript
|
{
"resource": ""
}
|
q47494
|
train
|
function (def, err) {
def.errors = def.errors || []
err.message = err.message.cyan
def.errors.push(err)
}
|
javascript
|
{
"resource": ""
}
|
|
q47495
|
RECESS
|
train
|
function RECESS(path, options, callback) {
this.path = path
this.output = []
this.errors = []
this.options = _.extend({}, RECESS.DEFAULTS, options)
path && this.read()
this.callback = callback
}
|
javascript
|
{
"resource": ""
}
|
q47496
|
train
|
function(event) {
var state = self.state();
for ( var i in self._callbacks ) {
self._callbacks[i].call(self._doc, event, state);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47497
|
train
|
function () {
if ( self._init ) {
return;
}
var event = 'visibilitychange';
if ( self._doc.webkitVisibilityState ) {
event = 'webkit' + event;
}
var listener = function () {
self._change.apply(self, arguments);
};
if ( self._doc.addEventListener ) {
self._doc.addEventListener(event, listener);
} else {
self._doc.attachEvent(event, listener);
}
self._init = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q47498
|
next
|
train
|
function next() {
counter = pending = 0;
// Check if there are no steps left
if (steps.length === 0) {
// Throw uncaught errors
if (arguments[0]) {
throw arguments[0];
}
return;
}
// Get the next step to execute
var fn = steps.shift();
results = [];
// Run the step in a try..catch block so exceptions don't get out of hand.
try {
lock = true;
var result = fn.apply(next, arguments);
} catch (e) {
// Pass any exceptions on through the next callback
next(e);
}
if (counter > 0 && pending == 0) {
// If parallel() was called, and all parallel branches executed
// synchronously, go on to the next step immediately.
next.apply(null, results);
} else if (result !== undefined) {
// If a synchronous return is used, pass it to the callback
next(undefined, result);
}
lock = false;
}
|
javascript
|
{
"resource": ""
}
|
q47499
|
seq
|
train
|
function seq() {
var fn;
var t = this;
for (var i = 0; i < arguments.length; i++) {
fn = arguments[i];
t = fn.call(t);
if (!t)
return false;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.