_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q57500
|
train
|
function (propType) {
return {
propType: propType,
preCtorInit: function focusProperty_preCtorInit(element, options, data, displayName, propName, value) {
options[propName] = value;
},
update: function focusProperty_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
var asyncToken = winjsComponent.data[propName];
asyncToken && clearImmediate(asyncToken);
asyncToken = setImmediate(function () {
winjsComponent.data[propName] = null;
winjsComponent.winControl[propName] = newValue;
});
}
},
dispose: function focusProperty_dispose(winjsComponent, propName) {
var asyncToken = winjsComponent.data[propName];
asyncToken && clearImmediate(asyncToken);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q57501
|
train
|
function (propType) {
return {
propType: propType,
preCtorInit: function domProperty_preCtorInit(element, options, data, displayName, propName, value) {
element[propName] = value;
},
update: function domProperty_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
winjsComponent.element[propName] = newValue;
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q57502
|
train
|
function (propType) {
return {
propType: propType,
update: function domAttribute_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
if (newValue !== null && newValue !== undefined) {
winjsComponent.element.setAttribute(propName, "" + newValue);
} else {
winjsComponent.element.removeAttribute(propName);
}
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q57503
|
event_update
|
train
|
function event_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
winjsComponent.winControl[propName.toLowerCase()] = newValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q57504
|
PropHandlers_warn
|
train
|
function PropHandlers_warn(warnMessage) {
return {
// Don't need preCtorInit because this prop handler doesn't have any side
// effects on the WinJS control. update also runs during initialization so
// update is just as good as preCtorInit for our use case.
update: function warn_update(winjsComponent, propName, oldValue, newValue) {
console.warn(winjsComponent.displayName + ": " + warnMessage);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q57505
|
PropHandlers_mountTo
|
train
|
function PropHandlers_mountTo(getMountPoint) {
return {
propType: React.PropTypes.element,
// Can't use preCtorInit because the mount point may not exist until the
// constructor has run.
update: function mountTo_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var version = (data.version || 0) + 1;
winjsComponent.data[propName] = {
// *mountComponent* may run asynchronously and we may queue it multiple
// times before it runs. *version* allows us to ensure only the latest
// version runs and the others are no ops.
version: version,
// *element* is the element to which we last mounted the component.
element: data.element
};
var mountComponent = function () {
if (version === winjsComponent.data[propName].version) {
var oldElement = winjsComponent.data[propName].element;
if (newValue) {
var newElement = getMountPoint(winjsComponent);
if (oldElement && oldElement !== newElement) {
ReactDOM.unmountComponentAtNode(oldElement);
}
ReactDOM.render(newValue, newElement);
winjsComponent.data[propName].element = newElement;
} else if (oldValue) {
oldElement && ReactDOM.unmountComponentAtNode(oldElement);
winjsComponent.data[propName].element = null;
}
}
};
// *isDeclarativeControlContainer* is a hook some WinJS controls provide
// (e.g. HubSection, PivotItem) to ensure that processing runs on the
// control only when the control is ready for it. This enables lazy loading
// of HubSections/PivotItems (e.g. load off screen items asynchronously in
// batches). Additionally, doing processing thru this hook guarantees that
// the processing won't run until the control is in the DOM.
var winControl = winjsComponent.winControl;
var queueProcessing = winControl.constructor.isDeclarativeControlContainer;
if (queueProcessing && typeof queueProcessing === "function") {
queueProcessing(winControl, mountComponent);
} else {
mountComponent();
}
},
dispose: function mountTo_dispose(winjsComponent, propName) {
var data = winjsComponent.data[propName] || {};
var element = data.element;
element && ReactDOM.unmountComponentAtNode(element);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q57506
|
mountTo_update
|
train
|
function mountTo_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var version = (data.version || 0) + 1;
winjsComponent.data[propName] = {
// *mountComponent* may run asynchronously and we may queue it multiple
// times before it runs. *version* allows us to ensure only the latest
// version runs and the others are no ops.
version: version,
// *element* is the element to which we last mounted the component.
element: data.element
};
var mountComponent = function () {
if (version === winjsComponent.data[propName].version) {
var oldElement = winjsComponent.data[propName].element;
if (newValue) {
var newElement = getMountPoint(winjsComponent);
if (oldElement && oldElement !== newElement) {
ReactDOM.unmountComponentAtNode(oldElement);
}
ReactDOM.render(newValue, newElement);
winjsComponent.data[propName].element = newElement;
} else if (oldValue) {
oldElement && ReactDOM.unmountComponentAtNode(oldElement);
winjsComponent.data[propName].element = null;
}
}
};
// *isDeclarativeControlContainer* is a hook some WinJS controls provide
// (e.g. HubSection, PivotItem) to ensure that processing runs on the
// control only when the control is ready for it. This enables lazy loading
// of HubSections/PivotItems (e.g. load off screen items asynchronously in
// batches). Additionally, doing processing thru this hook guarantees that
// the processing won't run until the control is in the DOM.
var winControl = winjsComponent.winControl;
var queueProcessing = winControl.constructor.isDeclarativeControlContainer;
if (queueProcessing && typeof queueProcessing === "function") {
queueProcessing(winControl, mountComponent);
} else {
mountComponent();
}
}
|
javascript
|
{
"resource": ""
}
|
q57507
|
PropHandlers_syncChildrenWithBindingList
|
train
|
function PropHandlers_syncChildrenWithBindingList(bindingListName) {
return {
preCtorInit: function syncChildrenWithBindingList_preCtorInit(element, options, data, displayName, propName, value) {
var latest = processChildren(displayName, value, {});
data[propName] = {
winjsChildComponents: latest.childComponents,
winjsChildComponentsMap: latest.childComponentsMap
};
options[bindingListName] = new WinJS.Binding.List(
latest.childComponents.map(function (winjsChildComponent) {
return winjsChildComponent.winControl;
})
);
},
update: function syncChildrenWithBindingList_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var oldChildComponents = data.winjsChildComponents || [];
var oldChildComponentsMap = data.winjsChildComponentsMap || {};
var latest = processChildren(winjsComponent.displayName, newValue, oldChildComponentsMap);
var bindingList = winjsComponent.winControl[bindingListName];
if (bindingList) {
applyEditsToBindingList(
bindingList,
diffArraysByKey(oldChildComponents, latest.childComponents)
);
} else {
winjsComponent.winControl[bindingListName] = new WinJS.Binding.List(latest.childComponents.map(function (winjsChildComponent) {
return winjsChildComponent.winControl;
}));
}
winjsComponent.data[propName] = {
winjsChildComponents: latest.childComponents,
winjsChildComponentsMap: latest.childComponentsMap
};
},
dispose: function syncChildrenWithBindingList_dispose(winjsComponent, propName) {
var data = winjsComponent.data[propName] || {};
var childComponents = data.winjsChildComponents || [];
childComponents.forEach(function (winjsChildComponent) {
winjsChildComponent.dispose();
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57508
|
train
|
function (winjsComponent, propName, oldValue, newValue) {
// TODO: dispose
ReactDOM.render(React.DOM.div(null, newValue), winjsComponent.winControl.element);
}
|
javascript
|
{
"resource": ""
}
|
|
q57509
|
addMetaProperty
|
train
|
function addMetaProperty (object, propName, value) {
defineProperty(object, propName, {
enumerable: false,
value
})
}
|
javascript
|
{
"resource": ""
}
|
q57510
|
functionParameters
|
train
|
function functionParameters(f) {
assert(typeof f === 'function');
var matches = functionRegex.exec(f.toString());
if(!matches || !matches[2].length) {
return [];
}
return matches[2].split(/[,\s]+/).filter(function(str) {
return str.length;
});
}
|
javascript
|
{
"resource": ""
}
|
q57511
|
train
|
function(overrides) {
var result = this.cache;
if(!result) {
result = construct(type, functionParameters(type).map(function(paramName) {
return self.resolve(paramName, overrides);
}));
}
if(doCache) {
this.cache = result;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q57512
|
deserializeProperty
|
train
|
function deserializeProperty (bunsenId, value, bunsenModel) {
const subModel = getSubModel(bunsenModel, bunsenId)
switch (subModel.type) {
case 'integer':
return parseInt(value)
case 'number':
return parseFloat(value)
default:
return value
}
}
|
javascript
|
{
"resource": ""
}
|
q57513
|
serializeFormValue
|
train
|
function serializeFormValue (formValue) {
if (formValue.country) {
formValue.country = countryCodeToName(formValue.country)
}
if (typeOf(formValue.latitude) === 'number') {
formValue.latitude = `${formValue.latitude}`
}
if (typeOf(formValue.longitude) === 'number') {
formValue.longitude = `${formValue.longitude}`
}
}
|
javascript
|
{
"resource": ""
}
|
q57514
|
normalizeItems
|
train
|
function normalizeItems ({data, labelAttribute, records, valueAttribute}) {
const labelAttr = labelAttribute || 'label'
const valueAttr = valueAttribute || 'id'
return data.concat(
records.map((record) => {
if (typeof record !== 'object') {
return {
label: `${record}`, // make sure label is a string
value: record
}
}
let label, value
if (labelAttr.indexOf('${') !== -1) {
label = utils.parseVariables(record, labelAttr)
} else {
label = get(record, labelAttr) || get(record, 'title')
}
if (valueAttr.indexOf('${') !== -1) {
value = utils.parseVariables(record, valueAttr)
} else {
value = get(record, valueAttr)
}
return {
label,
value
}
})
)
}
|
javascript
|
{
"resource": ""
}
|
q57515
|
shouldAddCurrentValue
|
train
|
function shouldAddCurrentValue ({items, valueRecord, labelAttribute, valueAttribute, filter}) {
const filterRegex = new RegExp(filter, 'i')
const valueRecordMatchesFilter = filterRegex.test(valueRecord.get(labelAttribute))
const itemsContainsValueRecord = items.find(item => item.value === valueRecord.get(valueAttribute))
return valueRecordMatchesFilter && !itemsContainsValueRecord
}
|
javascript
|
{
"resource": ""
}
|
q57516
|
train
|
function (rect) {
if (rect) {
this.context.clearRect(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
} else {
this.canvas.width = this.canvas.width
if (cc.FLIP_Y_AXIS) {
this.context.scale(1, -1)
this.context.translate(0, -this.canvas.height)
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57517
|
train
|
function (opts) {
var target = opts.target,
priority = opts.priority,
paused = opts.paused
var i, len
var entry = {target: target, priority: priority, paused: paused}
var added = false
if (priority === 0) {
this.updates0.push(entry)
} else if (priority < 0) {
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
if (priority < this.updatesNeg[i].priority) {
this.updatesNeg.splice(i, 0, entry)
added = true
break
}
}
if (!added) {
this.updatesNeg.push(entry)
}
} else /* priority > 0 */{
for (i = 0, len = this.updatesPos.length; i < len; i++) {
if (priority < this.updatesPos[i].priority) {
this.updatesPos.splice(i, 0, entry)
added = true
break
}
}
if (!added) {
this.updatesPos.push(entry)
}
}
this.hashForUpdates[target.id] = entry
}
|
javascript
|
{
"resource": ""
}
|
|
q57518
|
train
|
function (dt) {
var i, len, x
if (this.timeScale != 1.0) {
dt *= this.timeScale
}
var entry
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
entry = this.updatesNeg[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (i = 0, len = this.updates0.length; i < len; i++) {
entry = this.updates0[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (i = 0, len = this.updatesPos.length; i < len; i++) {
entry = this.updatesPos[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (x in this.hashForMethods) {
if (this.hashForMethods.hasOwnProperty(x)) {
entry = this.hashForMethods[x]
if (entry) {
for (i = 0, len = entry.timers.length; i < len; i++) {
var timer = entry.timers[i]
if (timer) {
timer.update(dt)
}
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57519
|
train
|
function (opts) {
if (!opts.target || !opts.method) {
return
}
var target = opts.target,
method = (typeof opts.method == 'function') ? opts.method : target[opts.method]
var element = this.hashForMethods[opts.target.id]
if (element) {
for (var i=0; i<element.timers.length; i++) {
// Compare callback function
if (element.timers[i].callback == method.bind(target)) {
var timer = element.timers.splice(i, 1)
timer = null
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57520
|
train
|
function (target) {
if (!target) {
return
}
var id = target.id,
elementUpdate = this.hashForUpdates[id]
if (elementUpdate) {
// Remove from updates list
if (elementUpdate.priority === 0) {
this.updates0.splice(this.updates0.indexOf(elementUpdate), 1)
} else if (elementUpdate.priority < 0) {
this.updatesNeg.splice(this.updatesNeg.indexOf(elementUpdate), 1)
} else /* priority > 0 */{
this.updatesPos.splice(this.updatesPos.indexOf(elementUpdate), 1)
}
}
// Release HashMethodEntry object
this.hashForUpdates[id] = null
}
|
javascript
|
{
"resource": ""
}
|
|
q57521
|
train
|
function () {
var i, x, entry
// Custom selectors
for (x in this.hashForMethods) {
if (this.hashForMethods.hasOwnProperty(x)) {
entry = this.hashForMethods[x]
this.unscheduleAllSelectorsForTarget(entry.target)
}
}
// Updates selectors
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
entry = this.updatesNeg[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
for (i = 0, len = this.updates0.length; i < len; i++) {
entry = this.updates0[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
for (i = 0, len = this.updatesPos.length; i < len; i++) {
entry = this.updatesPos[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57522
|
train
|
function (target) {
if (!target) {
return
}
// Custom selector
var element = this.hashForMethods[target.id]
if (element) {
element.paused = true
element.timers = []; // Clear all timers
}
// Release HashMethodEntry object
this.hashForMethods[target.id] = null
// Update selector
this.unscheduleUpdateForTarget(target)
}
|
javascript
|
{
"resource": ""
}
|
|
q57523
|
train
|
function (opts) {
var targetID = opts.target.id
var element = this.targets[targetID]
if (!element) {
element = this.targets[targetID] = {
paused: false,
target: opts.target,
actions: []
}
}
element.actions.push(opts.action)
opts.action.startWithTarget(opts.target)
}
|
javascript
|
{
"resource": ""
}
|
|
q57524
|
train
|
function (action) {
var targetID = action.originalTarget.id,
element = this.targets[targetID]
if (!element) {
return
}
var actionIndex = element.actions.indexOf(action)
if (actionIndex == -1) {
return
}
if (this.currentTarget == element) {
element.currentActionSalvaged = true
}
element.actions[actionIndex] = null
element.actions.splice(actionIndex, 1); // Delete array item
if (element.actions.length === 0) {
if (this.currentTarget == element) {
this.currentTargetSalvaged = true
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57525
|
train
|
function(opts) {
var tag = opts.tag,
targetID = opts.target.id
var element = this.targets[targetID]
if (!element) {
return null
}
for (var i = 0; i < element.actions.length; i++ ) {
if (element.actions[i] &&
(element.actions[i].tag === tag)) {
return element.actions[i]
}
}
// Not found
return null
}
|
javascript
|
{
"resource": ""
}
|
|
q57526
|
train
|
function (target) {
var targetID = target.id
var element = this.targets[targetID]
if (!element) {
return
}
delete this.targets[targetID]
// Delete everything in array but don't replace it incase something else has a reference
element.actions.splice(0, element.actions.length)
}
|
javascript
|
{
"resource": ""
}
|
|
q57527
|
train
|
function () {
var str = 'Usage: ' + path.basename(process.argv[1]) + ' ' + process.argv[2];
if (descriptors.opts.length) str += ' [options]';
if (descriptors.args.length) {
for (var i=0; i<descriptors.args.length; i++) {
if (descriptors.args[i].required) {
str += ' ' + descriptors.args[i].name;
} else {
str += ' [' + descriptors.args[i].name + ']';
}
}
}
str += '\n';
for (var i=0; i<descriptors.opts.length; i++) {
var opt = descriptors.opts[i];
if (opt.description) str += (opt.description) + '\n';
var line = '';
if (opt.short && !opt.long) line += '-' + opt.short;
else if (opt.long && !opt.short) line += '--' + opt.long;
else line += '-' + opt.short + ', --' + opt.long;
if (opt.value) line += ' <value>';
if (opt.required) line += ' (required)';
str += ' ' + line + '\n';
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
|
q57528
|
train
|
function (opts) {
var name = opts.name || opts
var frame = this.spriteFrames[name]
if (!frame) {
// No frame, look for an alias
var key = this.spriteFrameAliases[name]
if (key) {
frame = this.spriteFrames[key]
}
if (!frame) {
throw "Unable to find frame: " + name
}
}
return frame
}
|
javascript
|
{
"resource": ""
}
|
|
q57529
|
train
|
function (pos) {
var layerSize = this.layerSize,
tiles = this.tiles
if (pos.x < 0 || pos.y < 0 || pos.x >= layerSize.width || pos.y >= layerSize.height) {
throw "TMX Layer: Invalid position"
}
var tile,
gid = this.tileGIDAt(pos)
// if GID is 0 then no tile exists at that point
if (gid) {
var z = pos.x + pos.y * layerSize.width
tile = this.getChild({tag: z})
}
return tile
}
|
javascript
|
{
"resource": ""
}
|
|
q57530
|
read
|
train
|
function read(file) {
var data = fs.readFileSync(file, 'ascii');
// Strip comments
data = data.replace(/#.*/g, '');
var lines = data.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i].trim();
if (!line) {
continue;
}
var words = line.split(/\s/),
type = words.shift(),
suffixes = words;
for (var j = 0, jen = suffixes.length; j < jen; j++) {
var suff = suffixes[j].trim();
if (!suff) {
continue;
}
addType(type, '.' + suff);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57531
|
train
|
function (opts) {
var name = opts.name,
animation = opts.animation
this.animations[name] = animation
}
|
javascript
|
{
"resource": ""
}
|
|
q57532
|
train
|
function (opts) {
var objectName = opts.name
var object = null
this.objects.forEach(function (item) {
if (item.name == objectName) {
object = item
}
})
if (object !== null) {
return object
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57533
|
train
|
function (key) {
var next = false
if (~key.indexOf('.')) {
var tokens = key.split('.');
key = tokens.shift();
next = tokens.join('.');
}
var accessor = getAccessors(this)[key],
val;
if (accessor) {
val = accessor.target.get(accessor.key);
} else {
// Call getting function
if (this['get_' + key]) {
val = this['get_' + key]();
} else {
val = this[key];
}
}
if (next) {
return val.get(next);
} else {
return val;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57534
|
train
|
function (key, value) {
var accessor = getAccessors(this)[key],
oldVal = this.get(key);
this.triggerBeforeChanged(key, oldVal);
if (accessor) {
accessor.target.set(accessor.key, value);
} else {
if (this['set_' + key]) {
this['set_' + key](value);
} else {
this[key] = value;
}
}
this.triggerChanged(key, oldVal);
}
|
javascript
|
{
"resource": ""
}
|
|
q57535
|
train
|
function (kvp) {
for (var x in kvp) {
if (kvp.hasOwnProperty(x)) {
this.set(x, kvp[x]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57536
|
train
|
function (key, target, targetKey, noNotify) {
targetKey = targetKey || key;
var self = this;
this.unbind(key);
var oldVal = this.get(key);
// When bound property changes, trigger a 'changed' event on this one too
getBindings(this)[key] = events.addListener(target, targetKey.toLowerCase() + '_changed', function (oldVal) {
self.triggerChanged(key, oldVal);
});
addAccessor(this, key, target, targetKey, noNotify);
}
|
javascript
|
{
"resource": ""
}
|
|
q57537
|
train
|
function () {
var keys = [],
bindings = getBindings(this);
for (var k in bindings) {
if (bindings.hasOwnProperty(k)) {
this.unbind(k);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57538
|
train
|
function (i, value) {
this.array.splice(i, 0, value);
this.set('length', this.array.length);
events.trigger(this, 'insert_at', i);
}
|
javascript
|
{
"resource": ""
}
|
|
q57539
|
train
|
function (i) {
var oldVal = this.array[i];
this.array.splice(i, 1);
this.set('length', this.array.length);
events.trigger(this, 'remove_at', i, oldVal);
return oldVal;
}
|
javascript
|
{
"resource": ""
}
|
|
q57540
|
round10
|
train
|
function round10(value, exp) {
var type = 'round';
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
|
javascript
|
{
"resource": ""
}
|
q57541
|
Director
|
train
|
function Director () {
if (Director._instance) {
throw new Error('Director instance already exists')
}
this.sceneStack = []
this.window = parent.window
this.document = this.window.document
// Prevent writing to some properties
util.makeReadonly(this, 'canvas context sceneStack winSize isReady document window container isTouchScreen isMobile'.w)
}
|
javascript
|
{
"resource": ""
}
|
q57542
|
train
|
function () {
if (!Director._instance) {
if (window.navigator.userAgent.match(/(iPhone|iPod|iPad|Android)/)) {
Director._instance = new DirectorTouchScreen()
} else {
Director._instance = new this()
}
}
return Director._instance
}
|
javascript
|
{
"resource": ""
}
|
|
q57543
|
train
|
function () {
var is = this.inScene,
os = this.outScene
/* clean up */
is.visible = true
is.position = geo.PointZero()
is.scale = 1.0
is.rotation = 0
os.visible = false
os.position = geo.PointZero()
os.scale = 1.0
os.rotation = 0
Scheduler.sharedScheduler.schedule({
target: this,
method: this.setNewScene,
interval: 0
})
}
|
javascript
|
{
"resource": ""
}
|
|
q57544
|
train
|
function(manifest, compilation, props) {
const outputFolder = compilation.options.output.path;
const outputFile = path.join(outputFolder, props.fileName);
fse.outputFileSync(outputFile, manifest);
}
|
javascript
|
{
"resource": ""
}
|
|
q57545
|
train
|
function(compilation, assetName) {
if (!compilation || !compilation.cache || typeof compilation.cache !== 'object') {
return null;
}
const cacheKeys = Object.keys(compilation.cache);
for (let keyIndex = 0; keyIndex < cacheKeys.length; keyIndex++) {
const cache = compilation.cache[cacheKeys[keyIndex]];
if (cache.assets && assetName in cache.assets) {
return cache.rawRequest;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q57546
|
hasFontLoaded
|
train
|
function hasFontLoaded (window, fontName) {
var testSize = 16
if (!fontTestElement) {
fontTestElement = window.document.createElement('canvas')
fontTestElement.width = testSize
fontTestElement.height = testSize
fontTestElement.style.display = 'none'
ctx = fontTestElement.getContext('2d')
window.document.body.appendChild(fontTestElement)
}
fontTestElement.width = testSize
ctx.fillStyle = 'rgba(0, 0, 0, 0)'
ctx.fillRect(0, 0, testSize, testSize)
ctx.font = testSize + "px __cc2d_" + fontName
ctx.fillStyle = 'rgba(255, 255, 255, 1)'
ctx.fillText("M", 0, testSize);
var pixels = ctx.getImageData(0, 0, testSize, testSize).data
for (var i = 0; i < testSize * testSize; i++) {
if (pixels[i * 4] != 0) {
fontTestElement.parentNode.removeChild(fontTestElement)
fontTestElement = null
return true
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q57547
|
train
|
function (opts) {
var layerName = opts.name,
layer = null
this.children.forEach(function (item) {
if (item instanceof TMXLayer && item.layerName == layerName) {
layer = item
}
})
if (layer !== null) {
return layer
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57548
|
train
|
function (opts) {
var objectGroupName = opts.name,
objectGroup = null
this.objectGroups.forEach(function (item) {
if (item.name == objectGroupName) {
objectGroup = item
}
})
if (objectGroup !== null) {
return objectGroup
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57549
|
generateNSISScript
|
train
|
function generateNSISScript(files, callback) {
sys.puts('Generating NSIS script');
var installFileList = ' SetOverwrite try\n',
removeFileList = '',
removeDirList = '';
files = files.filter(function(file) {
// Ignore node-builds for other platforms
if (~file.indexOf('node-builds') && !~file.indexOf('cyg') && !~file.indexOf('tmp') && !~file.indexOf('etc')) {
return;
}
return file;
});
// Generate the install and remove lists
var prevDirname, i, len;
for (i = 0, len = files.length; i < len; i++) {
var file = files[i];
var dirname = path.dirname(file);
if (dirname != prevDirname) {
prevDirname = dirname;
installFileList += ' SetOutPath "$INSTDIR\\' + dirname.replace(/\//g, '\\') + '"\n';
removeDirList += ' RMDir "$INSTDIR\\' + dirname.replace(/\//g, '\\') + '"\n';
}
var m;
if ((m = file.match(/\/?(README|LICENSE)(.md)?$/))) {
// Rename README and LICENSE so they end in .txt
installFileList += ' File /oname=' + m[1] + '.txt "${ROOT_PATH}\\' + file.replace(/\//g, '\\') + '"\n';
} else {
installFileList += ' File "${ROOT_PATH}\\' + file.replace(/\//g, '\\') + '"\n';
}
removeFileList += ' Delete "$INSTDIR\\' + file.replace(/\//g, '\\') + '"\n';
}
var tmp = new Template(fs.readFileSync(path.join(__dirname, 'installer_nsi.template'), 'utf8'));
var data = tmp.substitute({
root_path: path.join(__dirname, '../..'),
output_path: OUTPUT_PATH,
version: 'v' + VERSION,
install_file_list: installFileList,
remove_file_list: removeFileList,
remove_dir_list: removeDirList
});
callback(data);
}
|
javascript
|
{
"resource": ""
}
|
q57550
|
findFilesToPackage
|
train
|
function findFilesToPackage(dir, callback) {
var cwd = process.cwd();
process.chdir(dir);
var gitls = spawn('git', ['ls-files']),
// This gets the full path to each file in each submodule
subls = spawn('git', ['submodule', 'foreach', 'for file in `git ls-files`; do echo "$path/$file"; done']);
// List all node_modules
modls = spawn('find', ['node_modules']);
var mainFileList = '';
gitls.stdout.on('data', function (data) {
mainFileList += data;
});
gitls.on('exit', returnFileList);
var subFileList = '';
subls.stdout.on('data', function (data) {
subFileList += data;
});
subls.on('exit', returnFileList);
var modFileList = '';
modls.stdout.on('data', function (data) {
modFileList += data;
});
modls.on('exit', returnFileList);
var lsCount = 0;
function returnFileList(code) {
lsCount++;
if (lsCount < 3) {
return;
}
process.chdir(cwd);
// Convert \n separated list of filenames into a sorted array
var fileList = (mainFileList.trim() + '\n' + subFileList.trim() + '\n' + modFileList.trim()).split('\n').filter(function(file) {
// Ignore entering submodule messages
if (file.indexOf('Entering ') === 0) {
return;
}
// Ignore hidden and backup files
if (file.split('/').pop()[0] == '.' || file[file.length - 1] == '~') {
return;
}
// Submodules appear in ls-files but aren't files. Skip them
if (fs.statSync(path.join(dir, file)).isDirectory()) {
return;
}
return file;
}).sort();
callback(fileList);
}
}
|
javascript
|
{
"resource": ""
}
|
q57551
|
train
|
function () {
return new SpriteFrame({rect: this.rect, rotated: this.rotated, offset: this.offset, originalSize: this.originalSize, texture: this.texture})
}
|
javascript
|
{
"resource": ""
}
|
|
q57552
|
handleResolution
|
train
|
function handleResolution(options, ws, resIdx, config, progress, callback) {
// Resolution object
let res = options.tiles.resolutions[resIdx];
// Workspace of this resolutions
let resWs;
if (options.tiles.resolutions.length == 1) {
resWs = ws;
} else {
resWs = ws + '/' + res.id;
}
// Create directory of resolution workspace
fs.ensureDir(resWs, (err) => {
// Error
if (err) {
// Directory could not be created.
// Call callback function with error.
callback(err);
} else {
// No errors
// Handle all wms
handleWMS(options, resWs, res, 0, config, progress, (err) => {
// Error
if (err) {
// It could not be handled all wms.
// Call callback function with error.
callback(err);
} else {
// No errors
// Raise resolution index
resIdx++;
// New resolution index exists
if (resIdx < options.tiles.resolutions.length) {
handleResolution(options, ws, resIdx, config, progress, callback);
} else {
// New resolution index does not exists
// Call callback function without errors. All resolution
// were
// handled.
callback(null);
}
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q57553
|
writeTile
|
train
|
function writeTile(file, url, request, callback) {
// Result of request
let res = null;
// FileWriteStream
let fileStream = fs.createWriteStream(file);
// Register finish callback of FileWriteStream
fileStream.on('finish', () => {
callback(null, res);
});
// Register error callback of FileWriteStream
fileStream.on('error', (err) => {
callback(err, res);
});
// Request object
let req = request.get(url);
// Register error callback of request
req.on('error', (err) => {
callback(err, res);
});
// Register response callback of request
req.on('response', (response) => {
res = response;
});
// Start download
req.pipe(fileStream);
}
|
javascript
|
{
"resource": ""
}
|
q57554
|
train
|
function() {
//var logger = Logger.initialize(mockChildProcessFactory);
function MockChildProcess() {}
MockChildProcess.prototype.run = function run (command, args) {
// logger.debug("CHILD PROCESS MOCK!");
// logger.debug("command: "+command);
// logger.debug("args: "+args);
// logger.debug("env: "+env);
// logger.debug("code: "+code);
if ((command === 'ipmitool') && _.contains(args, 'status')) {
// power status call, return a "success"
return Promise.resolve({
stdout: 'Chassis Power is on'
});
}
};
return MockChildProcess;
}
|
javascript
|
{
"resource": ""
}
|
|
q57555
|
train
|
function() {
function MockWaterline() {}
MockWaterline.prototype.nodes = {};
MockWaterline.prototype.nodes.findByIdentifier = function (nodeId) {
//return instance of a node with settings in it...
return Promise.resolve({
obmSettings: [
{
service: 'ipmi-obm-service',
config: {
'user': 'ADMIN',
'password': 'ADMIN',
'host': '192.192.192.192'
}
}
],
id: nodeId
});
};
return new MockWaterline();
}
|
javascript
|
{
"resource": ""
}
|
|
q57556
|
_adjustIpStrFormat
|
train
|
function _adjustIpStrFormat(ipString) {
var ip = ipString.split('.');
ipString = '';
for (var i = 0; i < ip.length; i += 1) {
switch (ip[i].length) {
case 1:
ip[i] = '00' + ip[i];
break;
case 2:
ip[i] = '0' + ip[i];
break;
default:
break;
}
ipString += ip[i];
}
return ipString.trim();
}
|
javascript
|
{
"resource": ""
}
|
q57557
|
getRequestObject
|
train
|
function getRequestObject(config, url) {
if (!request) {
// Init request object
request = require('request').defaults({
'headers': {
'User-Agent': config.request.userAgent
},
strictSSL: false,
timeout: config.request.timeout
});
}
if (!requestProxy) {
// If internet proxy is set
if (config.request.proxy) {
// String of username and password
let userPass = '';
if (config.request.proxy.http.user) {
if (config.request.proxy.http.password) {
userPass = encodeURIComponent(config.request.proxy.http.user) + ':' + encodeURIComponent(config.request.proxy.http.password) + '@';
}
}
// Init request object with internet proxy
requestProxy = request.defaults({
'headers': {
'User-Agent': config.request.userAgent
},
strictSSL: false,
timeout: config.request.timeout,
'proxy': 'http://' + userPass + config.request.proxy.http.host + ':' + config.request.proxy.http.port
});
}
}
let ret = request;
if (config.request.proxy) {
ret = requestProxy;
for (let int = 0; int < config.request.proxy.http.exclude.length; int++) {
if (url.includes(config.request.proxy.http.exclude[int])) {
ret = request;
break;
}
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q57558
|
Logger
|
train
|
function Logger (module) {
// Set the intiial module to the provided string value if present.
this.module = module !== undefined ? module.toString() : 'No Module';
// If the module is a function then we'll look for di.js annotations to get the
// provide string.
if (_.isFunction(module)) {
if (module.annotations && module.annotations.length) {
// Detect DI provides
var provides = _.detect(module.annotations, function (annotation) {
return _.has(annotation, 'token');
});
// If provides is present use that.
if (provides) {
this.module = provides.token;
return;
}
}
// If no provides then use the function.
if (module.name) {
this.module = module.name;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57559
|
getSpecifierIdentifiers
|
train
|
function getSpecifierIdentifiers(specifiers = [], withPath = false) {
const collection = [];
function loop(path, index) {
const node = path.node
const item = !withPath ? node.local.name : { path, name: node.local.name }
switch (node.type) {
case 'ImportDefaultSpecifier':
case 'ImportSpecifier':
case 'ImportNamespaceSpecifier':
collection.push(item);
break;
}
}
specifiers.forEach(loop);
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q57560
|
UINT32
|
train
|
function UINT32 (l, h) {
if ( !(this instanceof UINT32) )
return new UINT32(l, h)
this._low = 0
this._high = 0
this.remainder = null
if (typeof h == 'undefined')
return fromNumber.call(this, l)
if (typeof l == 'string')
return fromString.call(this, l, h)
fromBits.call(this, l, h)
}
|
javascript
|
{
"resource": ""
}
|
q57561
|
fromString
|
train
|
function fromString (s, radix) {
var value = parseInt(s, radix || 10)
this._low = value & 0xFFFF
this._high = value >>> 16
return this
}
|
javascript
|
{
"resource": ""
}
|
q57562
|
GetCatalogValuesJob
|
train
|
function GetCatalogValuesJob(options, context, taskId){
GetCatalogValuesJob.super_.call(this, logger, options, context, taskId);
this.nodeId = context.target;
this.options = options;
this.logger = logger;
}
|
javascript
|
{
"resource": ""
}
|
q57563
|
createGetMap
|
train
|
function createGetMap(wms, bbox, width, height) {
let getmap = wms.getmap.url;
for (let key in wms.getmap.kvp) {
getmap += encodeURIComponent(key) + '=' + encodeURIComponent(wms.getmap.kvp[key]) + '&';
}
getmap += 'BBOX=' + encodeURIComponent(bbox) + '&';
getmap += 'WIDTH=' + encodeURIComponent(width) + '&';
getmap += 'HEIGHT=' + encodeURIComponent(height) + '&';
return getmap;
}
|
javascript
|
{
"resource": ""
}
|
q57564
|
handleWMS
|
train
|
function handleWMS(options, ws, res, wmsIdx, config, progress, callback) {
// WMS object
let wms = options.wms[wmsIdx];
// Workspace of this WMS
let wmsWs = ws;
if (options.wms.length > 1) {
wmsWs += '/' + wms.id;
}
// Create directory of WMS workspace
fs.ensureDir(wmsWs, function (err) {
// Error
if (err) {
// Directory could not be created.
// Call callback function with error.
callback(err);
} else {
// No errors
// Calculate parameters of bbox
let bbox = {};
bbox.widthM = options.task.area.bbox.xmax - options.task.area.bbox.xmin;
bbox.heightM = options.task.area.bbox.ymax - options.task.area.bbox.ymin;
bbox.widthPx = bbox.widthM / res.groundResolution;
bbox.heightPx = bbox.heightM / res.groundResolution;
// Calculate parameters of tiles
let tiles = {};
tiles.sizePx = options.tiles.maxSizePx - 2 * options.tiles.gutterPx;
tiles.sizeM = tiles.sizePx * res.groundResolution;
tiles.xCount = Math.ceil(bbox.widthPx / tiles.sizePx);
tiles.yCount = Math.ceil(bbox.heightPx / tiles.sizePx);
tiles.xSizeOverAllPx = tiles.xCount * tiles.sizePx;
tiles.ySizeOverAllPx = tiles.yCount * tiles.sizePx;
tiles.gutterM = options.tiles.gutterPx * res.groundResolution;
tiles.x0 = options.task.area.bbox.xmin - (((tiles.xSizeOverAllPx - bbox.widthPx) / 2.0) * res.groundResolution);
tiles.y0 = options.task.area.bbox.ymax + (((tiles.ySizeOverAllPx - bbox.heightPx) / 2.0) * res.groundResolution);
// Handle all tiles
handleTiles(options, wms, wmsWs, tiles, 0, 0, res.groundResolution, config, progress, function (err) {
// Error
if (err) {
// Could not handle tiles
// Call callback function with error.
callback(err);
} else {
// No errors
// Raise wms index
wmsIdx++;
// Handle next WMS
if (wmsIdx < options.wms.length) {
handleWMS(options, ws, res, wmsIdx, config, progress, callback);
} else {
// All WMS were handled
// Call callback function without errors
callback(null);
}
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q57565
|
determineGroundResolution
|
train
|
function determineGroundResolution(res) {
//iterate over all resolutions
for (let int = 0; int < res.length; int++) {
let r = res[int];
//calculate the resolution if not available
if (!r.groundResolution) {
r.groundResolution = (0.0254 * r.scale) / r.dpi;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57566
|
parseSnmpLine
|
train
|
function parseSnmpLine(line) {
if (typeof line !== 'string') {
throw new Error("Data is not in string format");
}
var data = line.trim();
var errString = 'No Such Object available on this agent at this OID';
if (data.indexOf(errString) >= 0) {
throw new Error(data);
}
// Messages that occur as a result of doing MIB translation on output
// We exclude "Cannot find module" and "Did not find *" messages because
// in some cases we walk the whole tree and there are may be vendor-specific
// mibs that we don't have installed.
if (data.indexOf('MIB search path') >= 0 ||
data.indexOf('Cannot find module') >= 0 ||
data.indexOf('Did not find') >= 0) {
return;
}
var parsed = data.split(' ');
return {
oid: parsed.shift(),
value: parsed.join(' ').replace(/["']/g, '') //remove "" in '"name"'
};
}
|
javascript
|
{
"resource": ""
}
|
q57567
|
parseSnmpData
|
train
|
function parseSnmpData(snmpData) {
var lines = snmpData.trim().split('\n');
return _.compact(_.map(lines, function(line) {
return parseSnmpLine(line);
}));
}
|
javascript
|
{
"resource": ""
}
|
q57568
|
DownloadFileJob
|
train
|
function DownloadFileJob(options, context, taskId) {
var self = this;
DownloadFileJob.super_.call(self, logger, options, context, taskId);
self.nodeId = self.context.target;
if (self.options.filePath) {
self.options.filePath = self.options.filePath.trim();
if (_.last(self.options.filePath) === '/') {
self.options.filePath = self.options.filePath.substring(0, self.options.filePath.length - 1);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57569
|
getVersion
|
train
|
function getVersion () {
const url = 'https://raw.githubusercontent.com/mapbox/node-sqlite3/master/package.json'
return new Promise((resolve, reject) => {
https.get(url, res => {
let data = ''
res.setEncoding('utf8')
if (res.statusCode !== 200) return reject(res.statusMessage)
res.on('data', chunk => { data += chunk })
res.on('end', () => resolve(JSON.parse(data).version))
})
})
}
|
javascript
|
{
"resource": ""
}
|
q57570
|
main
|
train
|
async function main () {
const version = await getVersion()
for (const MODULE of ELECTRON_MODULES) {
for (const PLATFORM of PLATFORMS) {
for (const ARCH of ARCHS) {
const name = getElectronName(MODULE, PLATFORM, ARCH)
const filename = name + '.tar.gz'
const url = getUrl(version, name)
const binary = await download(url).catch(error => console.error(error, url))
if (binary) {
console.info(`Success ${url}`)
fs.writeFileSync(filename, binary)
await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
fs.removeSync(filename)
}
}
}
}
for (const MODULE of MODULES) {
for (const PLATFORM of PLATFORMS) {
for (const ARCH of ARCHS) {
const name = getName(MODULE, PLATFORM, ARCH)
const filename = name + '.tar.gz'
const url = getUrl(version, name)
const binary = await download(url).catch(error => console.error(error, url))
if (binary) {
console.info(`Success ${url}`)
fs.writeFileSync(filename, binary)
await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
fs.removeSync(filename)
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57571
|
_parseControllerInfoOneDriveData
|
train
|
function _parseControllerInfoOneDriveData(dataBlock) {
//split output by empty line
var dataSegments = dataBlock.split(/\n/); //Divided by line
var drvObj = {};
_.forEach(dataSegments, function(data) {
data = data.trim();
// Ignore empty line
if (data.length === 0) {
return;
}
//Split key and value by "="
var fields = data.split("="); //Divided by "="
drvObj[fields[0]] = fields[1].trim();
});
return drvObj;
}
|
javascript
|
{
"resource": ""
}
|
q57572
|
_parseSmartOneDriveData
|
train
|
function _parseSmartOneDriveData(dataBlock) {
//split output by empty line
var dataSegments = dataBlock.split(/\r?\n\s*\r?\n/); //Divided by empty line
var drvObj = {};
_.forEach(dataSegments, function(data) {
data = data.trim();
//remove the empty data segment and the segment with smartctl version
if (data.length === 0 || data.match(/^smartctl\s([\d\.]+)\s/)) {
return;
}
var lines = data.split(/\r?\n/); //Divided by line
if (data.startsWith('=== START OF INFORMATION SECTION ===')) {
drvObj.Identity = _parseSmartInfoSection(lines);
}
else if (data.startsWith('=== START OF READ SMART DATA SECTION ===')) {
drvObj['Self-Assessment'] = _parseSmartSelfAssessment(lines);
}
else if (data.startsWith('General SMART Values')) {
drvObj.Capabilities = _parseSmartCapabilities(lines);
}
else if (data.startsWith('SMART Attributes Data Structure revision number:')) {
drvObj.Attributes = _parseSmartAttributes(lines);
}
else if (data.startsWith('SMART Error Log Version:')) {
drvObj['Error Log'] = _parseSmartErrorLog(lines);
}
else if (data.startsWith('SMART Self-test log structure revision number')) {
drvObj['Self-test Log'] = _parseSmartSelfTestLog(lines);
}
else if (data.startsWith(
'SMART Selective self-test log data structure revision number')) {
drvObj['Selective Self-test Log'] = _parseSmartSelectiveSelfTestLog(lines);
}
else {
//I don't find the regular pattern for some data segment, or I don't know how to
//well classify some data, so just put them in the 'Un-parsed Raw Data'.
if (_.isArray(drvObj['Un-parsed Raw Data'])) {
drvObj['Un-parsed Raw Data'].push(data);
}
else {
drvObj['Un-parsed Raw Data'] = [data];
}
}
});
return drvObj;
}
|
javascript
|
{
"resource": ""
}
|
q57573
|
_parseSmartInfoSection
|
train
|
function _parseSmartInfoSection(lines) {
/*
*Example data:
=== START OF INFORMATION SECTION ===
Device Model: Micron_P400e-MTFDDAK200MAR
Serial Number: 1144031E6FB3
LU WWN Device Id: 5 00a075 1031e6fb3
Firmware Version: 0135
User Capacity: 200,049,647,616 bytes [200 GB]
*/
var result = {};
//ignore the first line
for (var i = 1; i < lines.length; i+=1) {
_parseSmartColonLine(lines[i], result);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57574
|
_parseSmartSelfAssessment
|
train
|
function _parseSmartSelfAssessment(lines) {
/*
Example 1:
=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED
Example 2:
=== START OF READ SMART DATA SECTION ===
SMART Health Status: OK
*/
var result = {};
//ignore the first line
for (var i = 1; i < lines.length; i+=1) {
_parseSmartColonLine(lines[i], result);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57575
|
_parseSmartCapabilities
|
train
|
function _parseSmartCapabilities(lines) {
var combineLines = [];
var strBuf = '';
/*
The first line is 'General SMART Values:', it should be discarded.
Some of the entry information is divided into multiline,
so first we try to combine these lines to achieve a regular patter.
Below is the example data:
Offline data collection status: (0x84) Offline data collection activity
was suspended by an interrupting command from host.
Auto Offline Data Collection: Enabled.
*/
for (var i = 1; i < lines.length; i+=1) {
var firstChar = lines[i][0];
if (firstChar >= 'A' && firstChar <= 'Z') {
if (strBuf !== '') {
combineLines.push(strBuf);
}
strBuf = lines[i];
}
else {
if (strBuf[strBuf.length-1] !== '.') {
strBuf += ' ';
}
strBuf += lines[i].trim();
}
}
if (strBuf !== '') { // if this is ignored, the last capabilities entry will be missed.
combineLines.push(strBuf);
}
//After combination, each line will become something like this:
//name: (0x84) annotation1.annotation2.annotation3
var result = [];
_.forEach(combineLines, function(line) {
var arr = line.split(/:\s*\(\s*(\w+)\)\s*/);
var annotation = (arr[2] ? arr[2].split('.') : []);
if (annotation.length > 0 && annotation[annotation.length-1].length === 0) {
annotation.pop();
}
result.push({
'Name' : arr[0],
'Value' : arr[1] || '',
'Annotation' : annotation
});
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57576
|
_parseSmartAttributes
|
train
|
function _parseSmartAttributes(lines) {
var attrObj = {};
/* Example data:
SMART Attributes Data Structure revision number: 1
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED
1 Raw_Read_Error_Rate 0x0003 100 100 006 Pre-fail Always
3 Spin_Up_Time 0x0003 100 100 000 Pre-fail Always
4 Start_Stop_Count 0x0002 100 100 020 Old_age Always
*/
//Parse first line to get revision number
//Example data: "SMART Attributes Data Structure revision number: 16"
if (lines.length > 0) {
attrObj.Revision = (lines[0].substring(lines[0].lastIndexOf(' ') + 1)).trim();
}
attrObj['Attributes Table'] = _parseSmartTable(lines, 2, /\s+/);
return attrObj;
}
|
javascript
|
{
"resource": ""
}
|
q57577
|
_parseSmartErrorLog
|
train
|
function _parseSmartErrorLog(lines) {
var resultObj = {};
//Parse first line to get revision number
//Example data:
//SMART Error Log Version: 1
if (lines.length > 0) {
resultObj.Revision = (lines[0].substring(
lines[0].lastIndexOf(' ') + 1)).trim();
}
//TODO: need to implement the error log parser
resultObj['Error Log Table'] = [];
if (lines.length > 1 && lines[1].startsWith('No ')) {
return resultObj;
}
//resultObj['Error Log Table'] = _parseSmartTable(lines, 1);
return resultObj;
}
|
javascript
|
{
"resource": ""
}
|
q57578
|
_parseSmartTable
|
train
|
function _parseSmartTable(lines,
ignoreLinesCount,
regSplitRow,
funcCheckTableEnd)
{
/* Example 1:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED
1 Raw_Read_Error_Rate 0x0003 100 100 006 Pre-fail Always
3 Spin_Up_Time 0x0003 100 100 000 Pre-fail Always
4 Start_Stop_Count 0x0002 100 100 020 Old_age Always
5 Reallocated_Sector_Ct 0x0003 100 100 036 Pre-fail Always
9 Power_On_Hours 0x0003 100 100 000 Pre-fail Always
12 Power_Cycle_Count 0x0003 100 100 000 Pre-fail Always
190 Airflow_Temperature_Cel 0x0003 069 069 050 Pre-fail Always
Example 2:
Num Test_Description Status Remaining LifeTime
# 1 Vendor (0xff) Completed 00% 463
# 2 Vendor (0xff) Completed 00% 288
# 3 Extended offline Completed 00% 263
# 4 Short offline Completed 00% 263
*/
var resultObj = [];
var colHeaders;
regSplitRow = regSplitRow || /\s{2,}/; //default to split with more than 2 spaces
if (lines.length <= ignoreLinesCount + 1) { //should contains at least the column header row
return resultObj;
}
//The first line should be the column header
colHeaders = lines[ignoreLinesCount].split(/\s+/);
if (colHeaders[0].trim().length === 0) {
colHeaders.shift();
}
for (var i = ignoreLinesCount + 1; i < lines.length; i+=1) {
if (funcCheckTableEnd && funcCheckTableEnd(lines[i])) {
break; //skip early if reach the end of table
}
var arr = lines[i].split(regSplitRow);
if (arr[0].trim().length === 0) {
arr.shift();
}
var entry = {};
var j;
for (j = 0; j < colHeaders.length - 1; j += 1) {
entry[colHeaders[j]] = arr[j]; //Fill each column data
}
//There maybe more cells than the header, we append these cells to the last column.
//For example, the 'RAW_VALUE' in the attributes table may be like '31 (Min/Max 31/31)'
entry[colHeaders[j]] = arr.slice(j, arr.length).join(' ');
resultObj.push(entry);
}
return resultObj;
}
|
javascript
|
{
"resource": ""
}
|
q57579
|
findDriveWwidByIndex
|
train
|
function findDriveWwidByIndex(catalog, isEsx, driveIndex) {
var wwid = null;
_.forEach(catalog, function(entry) {
if (entry.identifier === driveIndex) {
wwid = isEsx ? entry.esxiWwid : entry.linuxWwid;
return false; //have found the result, so we can exit iteration early.
}
});
return wwid;
}
|
javascript
|
{
"resource": ""
}
|
q57580
|
getDriveIdCatalog
|
train
|
function getDriveIdCatalog(nodeId, filter) {
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'driveId'
}).then(function (catalog) {
if (!catalog || !_.has(catalog, 'data[0]')) {
return Promise.reject(
new Error('Could not find driveId catalog data.'));
}
return catalog.data;
}).filter(function (driveId) {
if (_.isEmpty(filter)) {
return true;
}
return _.indexOf(filter, driveId.identifier) > -1 ||
_.indexOf(filter, driveId.devName) > -1;
});
}
|
javascript
|
{
"resource": ""
}
|
q57581
|
getVirtualDiskCatalog
|
train
|
function getVirtualDiskCatalog(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-virtual-disks'
})
.then(function (virtualDiskCatalog) {
if (!_.has(virtualDiskCatalog, 'data.Controllers[0]')) {
return Promise.reject(
new Error('Could not find megaraid-virtual-disks catalog data.'));
}
return virtualDiskCatalog.data;
});
}
|
javascript
|
{
"resource": ""
}
|
q57582
|
getPhysicalDiskCatalog
|
train
|
function getPhysicalDiskCatalog(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-physical-drives'
})
.then(function(physicalDiskCatalog){
if (!_.has(physicalDiskCatalog, 'data')) {
return Promise.reject(
new Error('Could not find megaraid-physical-drives catalog data.'));
}
return physicalDiskCatalog.data;
});
}
|
javascript
|
{
"resource": ""
}
|
q57583
|
getRaidControllerVendor
|
train
|
function getRaidControllerVendor(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-controllers'
})
.then(function (controllerCatalog) {
if (!_.has(controllerCatalog, 'data.Controllers')) {
return Promise.reject(
new Error('Could not find megaraid-controllers catalog data.'));
}
var vendor,
controllerId,
controllerVendors = [];
var controllerDataList = _.get(controllerCatalog, 'data.Controllers');
_.forEach(controllerDataList, function(data){
vendor = _.get(data, '[Response Data][Scheduled Tasks].OEMID');
controllerId = _.get(data, '[Command Status][Controller]');
controllerVendors[controllerId] = vendor.toLowerCase();
});
return controllerVendors;
});
}
|
javascript
|
{
"resource": ""
}
|
q57584
|
getDriveIdCatalogExt
|
train
|
function getDriveIdCatalogExt(nodeId, filter, extendJbod) {
return getDriveIdCatalog(nodeId, filter)
.then(function (driveIds) {
// get virtualDisk data from megaraid-virtual-disks catalog
var foundVdHasValue = _.find(driveIds, function (driveId) {
return !_.isEmpty(driveId.virtualDisk);
});
if (!foundVdHasValue && !extendJbod) {
// If none of drives are VDs, and extend JBOD is not required,
// it is not necessary to extend Megaraid information.
return Promise.resolve(driveIds);
}
return Promise.all([
foundVdHasValue ? getVirtualDiskCatalog(nodeId) : Promise.resolve(),
extendJbod ? getPhysicalDiskCatalog(nodeId) : Promise.resolve(),
getRaidControllerVendor(nodeId)
])
.spread(function(virtualDiskData, physicalDiskData, controllerVendors){
return Promise.map(driveIds, function(driveId){
if (!_.isEmpty(driveId.virtualDisk)) {
return _getVdExtDriveIdCatalog(
nodeId,
driveId,
virtualDiskData,
controllerVendors
);
}
if (extendJbod){
return _getJbodExtDriveIdCatalog(
nodeId,
driveId,
physicalDiskData,
controllerVendors
);
}
return driveId;
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57585
|
_getVdExtDriveIdCatalog
|
train
|
function _getVdExtDriveIdCatalog(nodeId, driveId, virtualDiskData, vendors){
var match = driveId.virtualDisk.match(/^\/c(\d+)\/v(\d+)/);
if (!match) {
return driveId;
}
var vid = match[2];
var cid = match[1];
var vdInfo;
_.forEach(virtualDiskData.Controllers, function(controller) {
var vd = _.get(controller,
'Response Data[%s]'.format(driveId.virtualDisk));
if (vd) {
vdInfo = vd[0];
vdInfo.oemId = controller.oemId;
vdInfo.pdList = _.get(controller,
'Response Data[PDs for VD %d]'.format(vid)
);
return false; // break forEach
}
});
if(!vdInfo) {
// clear virtualDisk if no matched info found in catalog
driveId.virtualDisk = '';
return driveId;
}
// set extended info to driveId catalog
driveId.size = vdInfo.Size;
driveId.type = vdInfo.TYPE;
driveId.controllerId = cid;
driveId.physicalDisks = _.map(vdInfo.pdList, function (pd) {
// for more physical disk info, search megaraid-physical-drives
var eidslt = pd['EID:Slt'].split(':');
return {
deviceId : pd.DID,
enclosureId : eidslt[0],
slotId : eidslt[1],
size: pd.Size,
protocol: pd.Intf,
type: pd.Med,
model: pd.Model
};
});
driveId.deviceIds = _.map(driveId.physicalDisks, function (disk) {
return disk.deviceId;
});
driveId.slotIds = _.map(driveId.physicalDisks, function (disk) {
// slotId : /c0/e252/s10
return '/c%d/e%d/s%d'.format(cid, disk.enclosureId, disk.slotId);
});
// OEM id is Dell or LSI
driveId.controllerVendor = vendors[_.parseInt(cid)];
return driveId;
}
|
javascript
|
{
"resource": ""
}
|
q57586
|
_getJbodExtDriveIdCatalog
|
train
|
function _getJbodExtDriveIdCatalog(nodeId, driveId, physicalDiskData, vendors){
//Devide ID in SCSI ID is used to match megaraid DID
//This feature is only qualified on servers with one RAID card
//An alternative method is to use logic wwid
//to find "OS Device Name" in smart catalog and get megaraid DID
var scsiIds = driveId.scsiId.split(':');
var deviceId = scsiIds[2];
var controllerId = scsiIds[0];
/**
*physicalDiskCatalog.data example, not fully displayed:
* "Controllers": [
* {
* "Command Status": {
* "Controller": 0,
* "Description": "Show Drive Information Succeeded.",
* "Status": "Success"
* },
* "Response Data": {
* "Drive /c0/e252/s0": [
* {
* "DG": 0,
* "DID": 0,
* "EID:Slt": "252:0",
* "Intf": "SAS",
* "Med": "HDD",
* "Model": "ST1200MM0088 ",
* "PI": "N",
* "SED": "N",
* "SeSz": "512B",
* "Size": "1.091 TB",
* "Sp": "U",
* "State": "Onln"
* }
*/
var driveDataList,
driveBaseInfoList = {},
matchedBaseInfo,
matchedBaseInfoKey;
_.forEach(physicalDiskData.Controllers, function(controller){
if (controller['Command Status'].Controller.toString() === controllerId) {
driveDataList = controller['Response Data'];
return false;
}
});
//Filter Drive Basic information from Response Data
//Drive Basic information is the only one has array as element
_.forEach(driveDataList, function(driveInfo, key){
if(_.isArray(driveInfo)) {
driveBaseInfoList[key] = driveInfo[0];
}
});
_.forEach(driveBaseInfoList, function(info, key){
if(info.DID.toString() === deviceId){
matchedBaseInfoKey = key;
return false;
}
});
if (matchedBaseInfoKey ) {
// Base info key example:
// "Drive /c0/e252/s0"
var match = matchedBaseInfoKey.match(/.*\/c(\d+)\/e(\d+)\/s(\d+)/);
matchedBaseInfo = driveBaseInfoList[matchedBaseInfoKey];
driveId.controllerId = controllerId;
driveId.deviceIds = [matchedBaseInfo.DID];
driveId.slotIds = matchedBaseInfoKey.split(' ').slice(-1);
driveId.size = matchedBaseInfo.Size;
driveId.type = matchedBaseInfo.State;
driveId.controllerVendor = vendors[_.parseInt(controllerId)];
driveId.physicalDisks = [{
protocol: matchedBaseInfo.Intf,
model: matchedBaseInfo.Model,
deviceId: matchedBaseInfo.DID,
slotId: match[3],
size: matchedBaseInfo.Size,
type: matchedBaseInfo.Med,
enclosureId: match[2]
}];
}
return driveId;
}
|
javascript
|
{
"resource": ""
}
|
q57587
|
handleCommonOptions
|
train
|
function handleCommonOptions(options) {
// check the task timeout, if not specified, then set a default one.
if (!options.hasOwnProperty('_taskTimeout') && options.schedulerOverrides &&
options.schedulerOverrides.hasOwnProperty('timeout')) {
options._taskTimeout = options.schedulerOverrides.timeout;
}
if (typeof options._taskTimeout !== 'number') {
options._taskTimeout = 24 * 60 * 60 * 1000; //default to 24 hour timeout
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q57588
|
createWorldFile
|
train
|
function createWorldFile(x0, y0, res) {
let halfPxInM = res / 2.0;
let ret = res + '\n';
ret += '0.0' + '\n';
ret += '0.0' + '\n';
ret += '-' + res + '\n';
ret += x0 + halfPxInM + '\n';
ret += y0 - halfPxInM;
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q57589
|
ObmService
|
train
|
function ObmService(nodeId, obmServiceFactory, obmSettings, options) {
assert.object(obmSettings);
assert.object(obmSettings.config);
assert.string(obmSettings.service);
assert.func(obmServiceFactory);
assert.isMongoId(nodeId);
this.params = options || {};
this.retries = this.params.retries;
this.delay = this.params.delay;
if (this.params.delay !== 0) {
this.delay = this.params.delay || config.get('obmInitialDelay') || 500;
}
if (this.params.retries !== 0) {
this.retries = this.params.retries || config.get('obmRetries') || 6;
}
this.serviceFactory = obmServiceFactory;
this.obmConfig = obmSettings.config;
this.serviceType = obmSettings.service;
this.nodeId = nodeId;
}
|
javascript
|
{
"resource": ""
}
|
q57590
|
_getValidSku
|
train
|
function _getValidSku (node) {
if (node.sku) {
return waterline.skus.findOne({ id: node.sku }).then(function (sku) {
if (sku && sku.name) {
node.sku = sku.name;
}
else {
return Promise.reject();
}
});
}
else {
return Promise.reject();
}
}
|
javascript
|
{
"resource": ""
}
|
q57591
|
UINT64
|
train
|
function UINT64 (a00, a16, a32, a48) {
if ( !(this instanceof UINT64) )
return new UINT64(a00, a16, a32, a48)
this.remainder = null
if (typeof a00 == 'string')
return fromString.call(this, a00, a16)
if (typeof a16 == 'undefined')
return fromNumber.call(this, a00)
fromBits.apply(this, arguments)
}
|
javascript
|
{
"resource": ""
}
|
q57592
|
fromBits
|
train
|
function fromBits (a00, a16, a32, a48) {
if (typeof a32 == 'undefined') {
this._a00 = a00 & 0xFFFF
this._a16 = a00 >>> 16
this._a32 = a16 & 0xFFFF
this._a48 = a16 >>> 16
return this
}
this._a00 = a00 | 0
this._a16 = a16 | 0
this._a32 = a32 | 0
this._a48 = a48 | 0
return this
}
|
javascript
|
{
"resource": ""
}
|
q57593
|
fromString
|
train
|
function fromString (s, radix) {
radix = radix || 10
this._a00 = 0
this._a16 = 0
this._a32 = 0
this._a48 = 0
/*
In Javascript, bitwise operators only operate on the first 32 bits
of a number, even though parseInt() encodes numbers with a 53 bits
mantissa.
Therefore UINT64(<Number>) can only work on 32 bits.
The radix maximum value is 36 (as per ECMA specs) (26 letters + 10 digits)
maximum input value is m = 32bits as 1 = 2^32 - 1
So the maximum substring length n is:
36^(n+1) - 1 = 2^32 - 1
36^(n+1) = 2^32
(n+1)ln(36) = 32ln(2)
n = 32ln(2)/ln(36) - 1
n = 5.189644915687692
n = 5
*/
var radixUint = radixPowerCache[radix] || new UINT64( Math.pow(radix, 5) )
for (var i = 0, len = s.length; i < len; i += 5) {
var size = Math.min(5, len - i)
var value = parseInt( s.slice(i, i + size), radix )
this.multiply(
size < 5
? new UINT64( Math.pow(radix, size) )
: radixUint
)
.add( new UINT64(value) )
}
return this
}
|
javascript
|
{
"resource": ""
}
|
q57594
|
_findMatchingMac
|
train
|
function _findMatchingMac(nodeLldpData, lldpMacList) {
var relationsList = {};
return Promise.all(
_.forEach(_.keys(nodeLldpData.data), function (ethPort) {
//validate mac first
var lldpMac = catalogSearch.getPath(nodeLldpData.data[ethPort], 'chassis.mac');
if (!lldpMac) {
throw new Error('cant find mac address in lldp data for node ' +
nodeLldpData.node + ' port ' + ethPort);
}
if (_validateMacStrFormat(lldpMac)) {
lldpMac = _adjustMacStrFormat(lldpMac);
if (lldpMacList.indexOf(lldpMac) >= 0) {
var singleEntry = {
destMac: nodeLldpData.data[ethPort].chassis.mac,
destPort: nodeLldpData.data[ethPort].port.ifname
};
relationsList[ethPort] = singleEntry;
}
} else {
throw new Error('mac: ' + lldpMac + ' bad format',
+nodeLldpData.node + ' port ' + ethPort);
}
}))
.then(function () {
return Promise.resolve(relationsList);
});
}
|
javascript
|
{
"resource": ""
}
|
q57595
|
_adjustMacStrFormat
|
train
|
function _adjustMacStrFormat(macString) {
macString = macString.toLowerCase();
var mac = macString.split(':');
macString = '';
for (var i = 0; i < mac.length; i += 1) {
if (mac[i].length === 1) {
mac[i] = '0' + mac[i];
}
macString += mac[i];
}
return macString;
}
|
javascript
|
{
"resource": ""
}
|
q57596
|
cropTile
|
train
|
function cropTile(oldFile, newFile, tileSizePx, gutterSizePx, callback) {
if (oldFile.endsWith('.svg') && newFile.endsWith('.svg')) {
// vector images
fs.readFile(oldFile, { encoding: 'utf8' }, (err, content) => {
if (err) {
callback(err);
} else {
const parser = new xml2js.Parser({ async: false });
parser.parseString(content, (err, result) => {
if (err) {
callback(err);
} else {
const builder = new xml2js.Builder();
try {
const viewBox = result.svg['$'].viewBox.split(' ');
for (let i = 0; i < viewBox.length; i++) {
viewBox[i] = parseFloat(viewBox[i]);
}
viewBox[0] = viewBox[0] + gutterSizePx;
viewBox[1] = viewBox[1] + gutterSizePx;
viewBox[2] = viewBox[2] - gutterSizePx * 2;
viewBox[3] = viewBox[3] - gutterSizePx * 2;
result.svg['$'].viewBox = viewBox[0] + ' ' + viewBox[1] + ' ' + viewBox[2] + ' ' + viewBox[3];
const xml = builder.buildObject(result);
fs.writeFile(newFile, xml, { encoding: 'utf8' }, callback);
} catch (err) {
callback(err);
}
}
});
}
});
} else {
// raster images (and from vector to raster image as well)
let inExt = oldFile.substring(oldFile.length - 3, oldFile.length);
let outExt = newFile.substring(newFile.length - 3, newFile.length);
/*
* The conversion from to jpg and tif is wrong by default. The
* transparency will convert to black. It is correct, if the transparency will
* convert to white.
*
* That will fixed with the following code.
*/
if ((inExt == '' && outExt == 'jpg') || (inExt == '' && outExt == 'tif')) {
gm(oldFile).flatten().background('white').crop(tileSizePx, tileSizePx, gutterSizePx, gutterSizePx).write(newFile, (err) => {
callback(err);
});
} else {
gm(oldFile).crop(tileSizePx, tileSizePx, gutterSizePx, gutterSizePx).write(newFile, (err) => {
callback(err);
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57597
|
_verifyFiltering
|
train
|
function _verifyFiltering(filters, counts, data) {
var reading = data.data.alert.reading;
if (_.isEmpty(reading)) {
return false;
}
var filter = filters[0];
var count = counts[0];
var matched = true;
_.map(filter, function(value, key){
if (data.data.alert.reading[key] !== value) {
matched = false;
}
});
if (matched) {
count = count - 1;
if (count === 0){
filters.shift();
counts.shift();
} else {
counts[0] = count;
}
}
if (_.isEmpty(filters)){
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q57598
|
_extractEsxBootCfgValue
|
train
|
function _extractEsxBootCfgValue(data, pattern) {
var pos = data.indexOf(pattern);
if (pos >= 0) {
pos += pattern.length;
var lineEndPos = data.indexOf('\n', pos);
if (lineEndPos >= 0) {
return data.substring(pos, lineEndPos);
}
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q57599
|
RestJob
|
train
|
function RestJob(options, context, taskId){
var self = this;
self.options = options;
self.context = context;
RestJob.super_.call(self, logger, options, context, taskId);
self.restClient = new HttpTool();
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.