_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6400 | Menu | train | function Menu() {
ui.Emitter.call(this);
this.items = {};
this.el = $(html).hide().appendTo('body');
this.el.hover(this.deselect.bind(this));
$('html').click(this.hide.bind(this));
this.on('show', this.bindKeyboardEvents.bind(this));
this.on('hide', this.unbindKeyboardEvents.bind(this));
} | javascript | {
"resource": ""
} |
q6401 | Card | train | function Card(front, back) {
ui.Emitter.call(this);
this._front = front || $('<p>front</p>');
this._back = back || $('<p>back</p>');
this.template = html;
this.render();
} | javascript | {
"resource": ""
} |
q6402 | stringify | train | function stringify(name, attrs) {
var str = [];
str.push('<' + name);
each(function(val, key) {
str.push(' ' + key + '="' + val + '"');
}, attrs);
str.push('>');
// block
if (name !== 'img') {
str.push('</' + name + '>');
}
return str.join('');
} | javascript | {
"resource": ""
} |
q6403 | attributes | train | function attributes(node) {
var obj = {};
each(function(attr) {
obj[attr.name] = attr.value;
}, node.attributes);
return obj;
} | javascript | {
"resource": ""
} |
q6404 | train | function (source) {
var ast = parser.parseEval(source)
var array = ast.children.find((child) => child.kind === 'array')
return parseValue(array)
} | javascript | {
"resource": ""
} | |
q6405 | train | function(data) {
var tagDict = {};
if (data.tags) {
each(data.tags, function(tag) {
tagDict[tag.title] = tag.value;
});
}
return tagDict;
} | javascript | {
"resource": ""
} | |
q6406 | prefixKey | train | function prefixKey(key) {
if (self.nameSpace.length > 0 && !key.startsWith(self.nameSpace)) {
return `${self.nameSpace}:${key}`
}
return key;
} | javascript | {
"resource": ""
} |
q6407 | xmultipleObjects | train | function xmultipleObjects(parents, proxyTarget = Object.create(null)) {
// Create proxy that traps property accesses and forwards to each parent, returning the first defined value we find
const forwardingProxy = new Proxy(proxyTarget, {
get: function (proxyTarget, propertyKey) {
// The proxy... | javascript | {
"resource": ""
} |
q6408 | xmultipleClasses | train | function xmultipleClasses(parents) {
// A dummy constructor because a class can only extend something constructible
function ConstructibleProxyTarget() {}
// Replace prototype with a forwarding proxy to parents' prototypes
ConstructibleProxyTarget.prototype = xmultipleObjects(parents.map(parent => pare... | javascript | {
"resource": ""
} |
q6409 | removeItemsFromList | train | function removeItemsFromList(list, itemsToRemove) {
var result = [];
_.each(list, function (item) {
var valid = true;
for (var i = 0; i < itemsToRemove.length; i++) {
// if the item match one of the items to remove don't includ it in the result list
if (item.indexOf(ite... | javascript | {
"resource": ""
} |
q6410 | getItemsFromList | train | function getItemsFromList(list, itemsToGet) {
var result = [];
_.each(list, function (item) {
for (var i = 0; i < itemsToGet.length; i++) {
if (item.indexOf(itemsToGet[i]) === 0) {
result.push(item);
}
}
});
return result;
} | javascript | {
"resource": ""
} |
q6411 | removeFieldsFromObj | train | function removeFieldsFromObj(data, fieldsToRemove) {
_.each(fieldsToRemove, function (fieldToRemove) {
// if field to remove is in the data, just remove it and go to the next one
if (data[fieldToRemove]) {
delete data[fieldToRemove];
return true;
}
var field... | javascript | {
"resource": ""
} |
q6412 | getFieldsFromObj | train | function getFieldsFromObj(data, fieldsToGet) {
var newObj = {};
_.each(fieldsToGet, function (fieldToGet) {
// if the field to get is in the data, then just transfer it over and that is it
if (data.hasOwnProperty(fieldToGet)) {
newObj[fieldToGet] = data[fieldToGet];
retu... | javascript | {
"resource": ""
} |
q6413 | applyFilter | train | function applyFilter(data, restrictedFields, allowedFields) {
var filterFunc;
// if string, something like a sort where each word should be a value
var isString = _.isString(data);
if (isString) { data = data.split(' '); }
if (restrictedFields) {
filterFunc = _.isArray(data) ? removeItemsF... | javascript | {
"resource": ""
} |
q6414 | train | function(card) {
return (
<div>
<p>
<button onClick={() => card.setState({ n: 0 })}>
ZERO
</button>
<button onClick={() => card.setState(s => ({ n: s.n + 1 }))}>
INC
</button>
<button onClick={() => card.setState(s => ({ n: s.n ... | javascript | {
"resource": ""
} | |
q6415 | train | function(card) {
var bg = ['#333', '#ccc'][card.state];
return (
<div style={{
width: 100, height: 50,
lineHeight: '50px',
margin: '0 auto',
textAlign: 'center',
border: '1px solid black',
transition: 'background-color 3s',
backgroundColor: bg,
... | javascript | {
"resource": ""
} | |
q6416 | train | function(card) {
return devboard.DOMNode(
function render(node) {
node.innerHTML = (
'<button>I can count to: ' +
card.state +
'</button>'
);
node.onclick = () => card.setState(n => n + 1);
}
);
} | javascript | {
"resource": ""
} | |
q6417 | getSizeBrutal | train | function getSizeBrutal(unit, element) {
var testDIV = document.createElement('div')
testDIV.style['height'] = '128' + unit
element.appendChild(testDIV)
var size = getPropertyInPX(testDIV, 'height') / 128
element.removeChild(testDIV)
return size
} | javascript | {
"resource": ""
} |
q6418 | camelToKebab | train | function camelToKebab(str) {
// Matches all places where a two upper case chars followed by a lower case char are and split them with an hyphen
return str.replace(/([a-zA-Z])([A-Z][a-z])/g, (match, before, after) =>
`${before.toLowerCase()}-${after.toLowerCase()}`
).toLowerCase();
} | javascript | {
"resource": ""
} |
q6419 | wrapComponent | train | function wrapComponent(component, elementName) {
let bindableProps = [];
if (component.propTypes) {
bindableProps = Object.keys(component.propTypes).map(prop => bindable({
name: prop,
attribute: camelToKebab(prop),
changeHandler: 'updateProps',
defaultBindingMode: 1
}));
}
return... | javascript | {
"resource": ""
} |
q6420 | listWebm | train | function listWebm (...args) {
let board
let threadNo
let protocol
if (args[1] === undefined) {
;({ board, threadNo, protocol } = parseUrl(args[0]))
} else {
[ board, threadNo ] = args
args[2] = args[2] || {}
protocol = args[2].https ? 'https' : 'http'
}
const apiUrl = `${protocol}://a.4c... | javascript | {
"resource": ""
} |
q6421 | tightenDependenciesVersions | train | function tightenDependenciesVersions(grunt, deps) {
console.assert(deps, 'missing deps object');
Object.keys(deps).forEach(function (name) {
var version = deps[name];
warnOnLooseVersion(grunt, name, version);
version = tightenVersion(version);
deps[name] = version;
});
} | javascript | {
"resource": ""
} |
q6422 | parseUrl | train | function parseUrl (url) {
const regex = /(https?).*\/(.+)\/thread\/(\d+)/g
let protocol
let board
let threadNo
try {
[, protocol, board, threadNo] = regex.exec(url)
} catch (err) {
throw new Error('Invalid 4chan URL!')
}
return {
protocol,
board,
threadNo: Number.parseInt(threadNo)... | javascript | {
"resource": ""
} |
q6423 | train | function() {
var mix = {};
[].forEach.call(arguments, function(arg) {
for (var name in arg) {
if (arg.hasOwnProperty(name)) {
mix[name] = arg[name];
}
}
});
return mix;
} | javascript | {
"resource": ""
} | |
q6424 | wrap | train | function wrap(str, lineLength) {
str = (str || '').toString();
lineLength = lineLength || 76;
if (str.length <= lineLength) {
return str;
}
let result = [];
let pos = 0;
let chunkLength = lineLength * 1024;
while (pos < str.length) {
let wrappedLines = str
.... | javascript | {
"resource": ""
} |
q6425 | train | function (value) {
var process = value.split('-');
value = beyond.css.values;
for (var i in process) {
value = value[process[i]];
if (typeof value === 'undefined') return;
}
return value;
} | javascript | {
"resource": ""
} | |
q6426 | createKeywordWrapper | train | function createKeywordWrapper(keywordsToRun) {
var wrapper = function(next) {
var args = _.rest(arguments);
runner.run(keywordsToRun, keywords, args).then(next);
};
return wrapper;
} | javascript | {
"resource": ""
} |
q6427 | createKeywords | train | function createKeywords(args) {
// TODO Hmm.. Circular dependency... something smells here...
var validators = require('./validators');
var keys = [];
for(var i = 0; i < args.length; i++) {
var keyword = {name: args[i]};
if(_.isArray(args[i + 1])) {
i++;
... | javascript | {
"resource": ""
} |
q6428 | mergeArray | train | function mergeArray(arr, mergeItems) {
var mergeKeys = _.chain(mergeItems)
.keys(mergeItems)
.map(Number)
.value();
var maxId = _.max(mergeKeys);
return rangeWhile(function(i) {
return i < (maxId + 1) || arr.length;
}, function(i) {
return _.contains(mergeKeys,... | javascript | {
"resource": ""
} |
q6429 | areDefined | train | function areDefined() {
var objects = Array.prototype.slice.call(arguments);
for (var i = 0; i < objects.length; i++) {
if (objects[i] !== null && typeof objects[i] === 'undefined')
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q6430 | isObject | train | function isObject(obj) {
if (!obj || !obj.constructor || obj.constructor.name !== 'Object')
return false;
else return true;
} | javascript | {
"resource": ""
} |
q6431 | tap | train | function tap(collection, fn, debugOnly) {
if (!debugOnly || exports.debug) {
// Clone the original array to prevent tampering, and send each element to the tap
collection.slice().forEach(function(element) { fn.call(null, element); });
}
return collection;
} | javascript | {
"resource": ""
} |
q6432 | zipmap | train | function zipmap(collection) {
var arrays = Array.prototype.slice.call(arguments, 1);
return collection.map(function(element, i) {
var others = [];
for (var j = 0; j < arrays.length; j++) {
var el = arrays[j] && arrays[j][i];
others.push(el !== null... | javascript | {
"resource": ""
} |
q6433 | endsWith | train | function endsWith(str, ending) {
if (str.length - ending.length === str.lastIndexOf(ending))
return true;
else return false;
} | javascript | {
"resource": ""
} |
q6434 | find | train | function find (c, predicate) {
for (var i = 0; i < c.length; i++) {
if (predicate(c[i]))
return c[i];
}
return null;
} | javascript | {
"resource": ""
} |
q6435 | Key | train | function Key(name, code) {
this.name = name;
this.code = code;
// If a new Key is instantiated with a name that isn't
// in the internal keymap, make sure we add it
Key.internals.keymap[name] = Key.internals.keymap[name] || code;
} | javascript | {
"resource": ""
} |
q6436 | Combo | train | function Combo(key, meta) {
var keys = null;
if (arguments.length === 2 && meta instanceof Array) {
keys = meta;
}
else if (arguments.length >= 2) {
keys = Array.prototype.slice.call(arguments, 1);
}
else if (arguments.length === 1) {
t... | javascript | {
"resource": ""
} |
q6437 | constructMetaParams | train | function constructMetaParams(flags) {
if (!flags || !(flags instanceof Array)) {
flags = [ false, false, false, false ];
}
// Predicate to filter meta keys by
var isActive = function(m) { return m[1] === true; };
// Extractor
var extractKey = function(m) { r... | javascript | {
"resource": ""
} |
q6438 | render | train | function render ($$) {
$$ = ($$ === undefined || $$ === null) ? {} : $$;
var _ref = undefined;
var _res = '';
var _i = 0;
var __extends__ = null;
_res += 'var _require = function (mod) { \n if ((typeof mod === \"object\") && (mod.render != null))\n return mod;\n return ';
... | javascript | {
"resource": ""
} |
q6439 | _safeGetNode | train | function _safeGetNode(g, u) {
var V = g._nodes;
if (!(u in V)) {
throw new Error("Node not in graph: " + u);
}
return V[u];
} | javascript | {
"resource": ""
} |
q6440 | _shallowCopyAttrs | train | function _shallowCopyAttrs(src, dst) {
if (Object.prototype.toString.call(src) !== '[object Object]') {
throw new Error("Attributes are not an object: " + src);
}
for (var k in src) {
dst[k] = src[k];
}
} | javascript | {
"resource": ""
} |
q6441 | _shallowEqual | train | function _shallowEqual(lhs, rhs) {
var lhsKeys = Object.keys(lhs);
var rhsKeys = Object.keys(rhs);
if (lhsKeys.length !== rhsKeys.length) {
return false;
}
for (var k in lhs) {
if (lhs[k] !== rhs[k]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q6442 | transform | train | function transform (raw, protocol, board) {
const reducer = (acc, file) => acc.concat([{
filename: file.filename,
url: webmUrl(protocol, board, file.tim),
thumbnail: thumbUrl(protocol, board, file.tim)
}])
const payload = {
webms: raw.posts.filter(isWebm).reduce(reducer, [])
}
if (raw.posts[... | javascript | {
"resource": ""
} |
q6443 | convertItemsToProperties | train | function convertItemsToProperties(items) {
// The object that contains the converted items
const result = {}
// Loop through all the inserted items
_.mapKeys(items, (changes, itemId) => {
// Loop through changes for this item
_.mapKeys(changes, (value, property) => {
// Add basic... | javascript | {
"resource": ""
} |
q6444 | notify | train | function notify (doc) {
// find queue, find worker...
if (_.isArray(workers[doc.type]) && !_.isEmpty(workers[doc.type])) {
var wkr = workers[doc.type].shift();
// update doc as processing
db.atomic('dequeue', 'id', doc._id, function (err, body) {
if (err) {
log.error(err);
return w... | javascript | {
"resource": ""
} |
q6445 | train | function (request) {
let serialized = request.serialized;
serialized.application = beyond.params.name;
serialized = JSON.stringify(serialized);
let hash = serialized.split('').reduce(function (a, b) {
a = ((a << 5) - a) + b.charCodeAt(0);
return Math.abs(a & a);... | javascript | {
"resource": ""
} | |
q6446 | train | function (opts) {
opts = opts || {};
this.name = opts.name || 'unknown';
this.userId = opts.userId;
this.userRole = opts.userRole || 'anonymous';
this.acl = opts.acl || {};
this.permissions = opts.permissions || [];
} | javascript | {
"resource": ""
} | |
q6447 | train | function (config, ID) {
if (!ID) ID = '/';
if (typeof config[environment] === 'string') hosts[ID] = config[environment];
for (let element in config) {
let elementID = (ID === '/') ? '/' + element : ID + '/' + element;
if (typeof config[element] === 'object') iterate(c... | javascript | {
"resource": ""
} | |
q6448 | getBCHBalance | train | async function getBCHBalance(addr, verbose) {
try {
const result = await Wormhole.Address.details([addr])
if (verbose) console.log(result)
const bchBalance = result[0]
return bchBalance.balance
} catch (err) {
console.error(`Error in getBCHBalance: `, err)
console.log(`addr: ${addr}`)
... | javascript | {
"resource": ""
} |
q6449 | append | train | function append(compiler, value, node) {
if (typeof compiler.append !== 'function') {
return compiler.emit(value, node);
}
return compiler.append(value, node);
} | javascript | {
"resource": ""
} |
q6450 | train | function (obj, clone, keyTransformFunc) {
// primitive types don't need to be cloned or further traversed
if (obj === null || typeof (obj) !== 'object' || Object.prototype.toString.call(obj) === '[object Date]') return obj;
let result;
if (Array.isArray(obj)) {
// obj is an array, keys are num... | javascript | {
"resource": ""
} | |
q6451 | validateProxyField | train | function validateProxyField(fieldKey, value, isRequired = false, options = null) {
const fieldErrors = [];
if (isRequired) {
// Nullable error is already handled by AJV
if (value === null) return fieldErrors;
if (!value) {
const message = m('inputSchema.validation.required', ... | javascript | {
"resource": ""
} |
q6452 | daleChallGradeLevel | train | function daleChallGradeLevel(score) {
score = Math.floor(score)
if (score < 5) {
score = 4
} else if (score > 9) {
score = 10
}
return gradeMap[score].concat()
} | javascript | {
"resource": ""
} |
q6453 | reset | train | function reset() {
// reset for subsequent use
transIndex = 0;
image = null;
pixels = null;
indexedPixels = null;
colorTab = null;
closeStream = false;
firstFrame = true;
} | javascript | {
"resource": ""
} |
q6454 | analyzePixels | train | function analyzePixels() {
var len = pixels.length;
var nPix = len / 3;
indexedPixels = [];
var nq = new NeuQuant(pixels, len, sample);
// initialize quantizer
colorTab = nq.process(); // create reduced palette
// map image pixels to new palette
var k = 0;
for (var j = 0; j < nPix... | javascript | {
"resource": ""
} |
q6455 | findClosest | train | function findClosest(c) {
if (colorTab === null) return -1;
var r = (c & 0xFF0000) >> 16;
var g = (c & 0x00FF00) >> 8;
var b = (c & 0x0000FF);
var minpos = 0;
var dmin = 256 * 256 * 256;
var len = colorTab.length;
for (var i = 0; i < len;) {
var dr = r - (colorTab[i++] & 0xff);
... | javascript | {
"resource": ""
} |
q6456 | getImagePixels | train | function getImagePixels() {
var w = width;
var h = height;
pixels = [];
var data = image;
var count = 0;
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
var b = (i * w * 4) + j * 4;
pixels[count++] = data[b];
pixels[count++] = data[b + 1];
pix... | javascript | {
"resource": ""
} |
q6457 | writeGraphicCtrlExt | train | function writeGraphicCtrlExt() {
out.writeByte(0x21); // extension introducer
out.writeByte(0xf9); // GCE label
out.writeByte(4); // data block size
var transp;
var disp;
if (transparent === null) {
transp = 0;
disp = 0; // dispose = no action
} else {
transp = 1;
dis... | javascript | {
"resource": ""
} |
q6458 | writeCommentExt | train | function writeCommentExt() {
out.writeByte(0x21); // extension introducer
out.writeByte(0xfe); // comment label
out.writeByte(comment.length); // Block Size (s)
out.writeUTFBytes(comment);
out.writeByte(0); // block terminator
} | javascript | {
"resource": ""
} |
q6459 | writeImageDesc | train | function writeImageDesc() {
out.writeByte(0x2c); // image separator
WriteShort(0); // image position x,y = 0,0
WriteShort(0);
WriteShort(width); // image size
WriteShort(height);
// packed fields
if (firstFrame) {
// no LCT - GCT is used for first (or only) frame
out.writeByte(... | javascript | {
"resource": ""
} |
q6460 | writeLSD | train | function writeLSD() {
// logical screen size
WriteShort(width);
WriteShort(height);
// packed fields
out.writeByte((0x80 | // 1 : global color table flag = 1 (gct used)
0x70 | // 2-4 : color resolution = 7
0x00 | // 5 : gct sort flag = 0
palSize)); // 6-8 : gct size
out.write... | javascript | {
"resource": ""
} |
q6461 | writeNetscapeExt | train | function writeNetscapeExt() {
out.writeByte(0x21); // extension introducer
out.writeByte(0xff); // app extension label
out.writeByte(11); // block size
out.writeUTFBytes("NETSCAPE" + "2.0"); // app id + auth code
out.writeByte(3); // sub-block size
out.writeByte(1); // loop sub-block id
Writ... | javascript | {
"resource": ""
} |
q6462 | writePalette | train | function writePalette() {
out.writeBytes(colorTab);
var n = (3 * 256) - colorTab.length;
for (var i = 0; i < n; i++) out.writeByte(0);
} | javascript | {
"resource": ""
} |
q6463 | writePixels | train | function writePixels() {
var myencoder = new LZWEncoder(width, height, indexedPixels, colorDepth);
myencoder.encode(out);
} | javascript | {
"resource": ""
} |
q6464 | subscribe | train | function subscribe() {
console.log(' > ', 'init', ['xmlrpc_bin://' + thisHost + ':2031', 'test123']);
rpcClient.methodCall('init', ['xmlrpc_bin://' + thisHost + ':2031', 'test123'], function (err, res) {
console.log(err, res);
});
} | javascript | {
"resource": ""
} |
q6465 | unsubscribe | train | function unsubscribe() {
console.log(' > ', 'init', ['xmlrpc_bin://' + thisHost + ':2031', '']);
rpcClient.methodCall('init', ['xmlrpc_bin://' + thisHost + ':2031', ''], function (err, res) {
console.log(err, res);
process.exit(0);
});
setTimeout(function () {
console.log('force... | javascript | {
"resource": ""
} |
q6466 | restoreFn | train | function restoreFn(db) {
return db.map(function(amb) {
return Object.assign({}, amb, {action: JSONfn.parse(amb.action)});
});
} | javascript | {
"resource": ""
} |
q6467 | compileFn | train | function compileFn(db) {
return db.map(function(amb) {
return Object.assign({}, amb, {action: JSONfn.stringify(amb.action)});
});
return result;
} | javascript | {
"resource": ""
} |
q6468 | add | train | function add(object) {
if (!_isValidAmbush(object)) {
return false;
}
object.description = _cleanDescription(object.description);
if (!_belongToAStoredAmbush(object.id)) {
const newObject = Object.assign({}, object);
goblin.ambush.push(newObject);
goblin.ambushEmitter.emit('change', { type: 'add', value: ... | javascript | {
"resource": ""
} |
q6469 | remove | train | function remove(id) {
if (!_isValidId(id)) {
return false;
}
const oldValue = JSONfn.clone(goblin.ambush);
_.remove(goblin.ambush, function(current) {
return current.id === id;
});
goblin.ambushEmitter.emit('change', {
type: 'remove',
oldValue: oldValue
});
} | javascript | {
"resource": ""
} |
q6470 | update | train | function update(id, object) {
// Validations
if (!_isValidId(id)) {
return false;
}
// Action
const index = _getIndexOfId(id);
if (index > -1) {
if (_isValidAmbushOnUpdate(id, object)) {
const current = goblin.ambush[index];
const newAmbush = Object.assign({}, current, object);
newAmbush.descriptio... | javascript | {
"resource": ""
} |
q6471 | details | train | function details(id) {
if (!_isValidId(id)) {
return false;
}
const index = _getIndexOfId(id);
if (index === -1) {
return logger('AMBUSH_NOT_STORED_ID');
}
return goblin.ambush[index];
} | javascript | {
"resource": ""
} |
q6472 | list | train | function list(category){
let list = [];
if (category && typeof(category) === 'string') {
list = _(goblin.ambush).filter(function(current) {
return _.includes(current.category, category);
}).map('id').value();
} else {
list = _(goblin.ambush).map('id').value();
}
return list;
} | javascript | {
"resource": ""
} |
q6473 | run | train | function run(id, parameter, callback) {
if (!_isValidId(id)) {
return false;
}
if (callback && typeof(callback) !== 'function') {
logger('AMBUSH_NO_CALLBACK');
}
const index = _getIndexOfId(id);
if (index > -1) {
goblin.ambush[index].action(parameter, callback);
} else {
logger('AMBUSH_INVALID_REFEREN... | javascript | {
"resource": ""
} |
q6474 | _isValidAmbush | train | function _isValidAmbush(object) {
return _isValidObject(object) &&
_isValidId(object.id) &&
_isUniqueId(null, object.id) &&
_isValidCategory(object.category) &&
_isValidAction(object.action);
} | javascript | {
"resource": ""
} |
q6475 | _isValidAmbushOnUpdate | train | function _isValidAmbushOnUpdate(id, object) {
return _isValidObject(object) &&
_isValidNotRequired(object.id, _isValidId) &&
_isUniqueId(id, object.id) &&
_isValidNotRequired(object.category, _isValidCategory) &&
_isValidNotRequired(object.action, _isValidAction);
} | javascript | {
"resource": ""
} |
q6476 | _isUniqueId | train | function _isUniqueId(currentId, newId) {
if (
newId !== undefined &&
currentId !== newId &&
_belongToAStoredAmbush(newId)
) {
logger('AMBUSH_PROVIDED_ID_ALREADY_EXIST');
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q6477 | init | train | function init(cb) {
Storage.read(goblin.config.files.db, {}, function(err, db) {
if (err) {
return cb(err);
}
goblin.db = db;
cb();
})
} | javascript | {
"resource": ""
} |
q6478 | get | train | function get(point) {
if (point && typeof(point) === 'string') {
const tree = point.split(goblin.config.pointerSymbol);
let parent = goblin.db;
for (let i = 0; i < tree.length; i++) {
if(i !== tree.length-1) {
if(typeof parent[tree[i]] === 'undefined') {
// If there is no child here, won't be deeper... | javascript | {
"resource": ""
} |
q6479 | push | train | function push(data, point) {
if (!point) {
point = '';
} else if (typeof(point) === 'string') {
point = point + '.';
} else {
logger('DB_SAVE_INVALID_REFERENCE');
}
const newKey = point + randomstring.generate();
set(data, newKey, true);
goblin.goblinDataEmitter.emit('change', {
type: 'push',
value: d... | javascript | {
"resource": ""
} |
q6480 | set | train | function set(data, point, silent) {
if (!data || typeof(data) !== 'object') {
return logger('DB_SAVE_INVALID_DATA');
}
if (point && typeof(point) === 'string') {
const tree = point.split(goblin.config.pointerSymbol);
let parent = goblin.db;
for (let i = 0; i < tree.length; i++) {
if (i !== tree.length -... | javascript | {
"resource": ""
} |
q6481 | update | train | function update(data, point) {
if (!data || typeof(data) !== 'object') {
return logger('DB_SAVE_INVALID_DATA');
}
if (point && typeof(point) === 'string') {
const tree = point.split('.');
let parent = goblin.db;
for (let i = 0; i < tree.length; i++) {
if (i !== tree.length-1) {
if (typeof parent[tre... | javascript | {
"resource": ""
} |
q6482 | deleteFn | train | function deleteFn(point) {
if (point && typeof(point) === 'string') {
const tree = point.split('.');
let source = goblin.db;
return tree.every((node, i) => {
if (source[node] === undefined) {
logger('DB_DELETE_INVALID_POINT', node);
return false;
}
if (i === tree.length - 1) {
let oldValue... | javascript | {
"resource": ""
} |
q6483 | changeAddrFromMnemonic | train | function changeAddrFromMnemonic(mnemonic) {
// root seed buffer
const rootSeed = Wormhole.Mnemonic.toSeed(mnemonic)
// master HDNode
let masterHDNode
if (NETWORK === "testnet")
masterHDNode = Wormhole.HDNode.fromSeed(rootSeed, "testnet")
else masterHDNode = Wormhole.HDNode.fromSeed(rootSeed)
// HDNo... | javascript | {
"resource": ""
} |
q6484 | lastNonEmptyLine | train | function lastNonEmptyLine (linesArray) {
let idx = linesArray.length - 1
while (idx >= 0 && !linesArray[idx]) {
idx--
}
return idx
} | javascript | {
"resource": ""
} |
q6485 | writeToFile | train | function writeToFile(file) {
if (!writeQueue[file]) {
return;
}
// If not already saving then save, but using the object we make sure to take only
// the last changes.
// Truncate - https://stackoverflow.com/questions/35178903/overwrite-a-file-in-node-js
fs.truncate(file, err => {
const bef... | javascript | {
"resource": ""
} |
q6486 | resolveAllWriteQueueCallbacks | train | function resolveAllWriteQueueCallbacks(file, error) {
writeQueue[file].callbacks.forEach(cb => cb(error));
} | javascript | {
"resource": ""
} |
q6487 | escapeRegexString | train | function escapeRegexString(unescapedString, escapeCharsRegex) {
// Validate arguments.
if (Object.prototype.toString.call(unescapedString) !== '[object String]') {
throw new TypeError('Argument 1 should be a string.');
}
if (escapeCharsRegex === undefined) {
escapeCharsRegex = defaultEsc... | javascript | {
"resource": ""
} |
q6488 | parse | train | function parse(argv) {
argv = argv || process.argv.slice(2);
/**
* This is where the actual parsing happens, we can use array#reduce to
* iterate over the arguments and change it to an object. We can easily bail
* out of the loop by destroying `argv` array.
*
* @param {Object} argh The object that s... | javascript | {
"resource": ""
} |
q6489 | insert | train | function insert(argh, key, value, option) {
//
// Automatic value conversion. This makes sure we store the correct "type"
//
if ('string' === typeof value && !isNaN(+value)) value = +value;
if (value === 'true' || value === 'false') value = value === 'true';
var single = option.charAt(1) !== '-'
, prop... | javascript | {
"resource": ""
} |
q6490 | train | function(url, callback) {
// Check if user input protocol
if (url.indexOf('http://') < 0 && url.indexOf('https://') < 0) { // TODO: Turn this into its own function
url = 'http://' + url;
}
// Make request and fire callback
request.get(url.toLowerCase(), function(error, response, body) {
... | javascript | {
"resource": ""
} | |
q6491 | train | function(body) {
var $ = cheerio.load(body),
page = {};
// Meta signals
page.title = $('title').text() || null;
page.description = $('meta[name=description]').attr('content') || null;
page.author = $('meta[name=author]').attr('content') || null;
page.keywords = $('meta[name=keyword... | javascript | {
"resource": ""
} | |
q6492 | train | function(url, options, callback) {
var crawler = Crawler.crawl(url.toLowerCase()),
opts = options || {},
maxPages = opts.maxPages || 10,
parsedPages = [], // Store parsed pages in this array
seoParser = this.meta, // Reference to `meta` method to ca... | javascript | {
"resource": ""
} | |
q6493 | apiResponded | train | function apiResponded(apiResponse) {
// Convert XML to JS object
var parser = new xml2js.Parser({explicitArray:false});
parser.parseString(apiResponse, function (err, result) {
// If the method processes the response, give it back
// Otherwise call the original callback
if(typ... | javascript | {
"resource": ""
} |
q6494 | getTxInfo | train | async function getTxInfo() {
const retVal = await Wormhole.DataRetrieval.transaction(TXID)
console.log(`Info from TXID ${TXID}: ${JSON.stringify(retVal, null, 2)}`)
} | javascript | {
"resource": ""
} |
q6495 | train | function(data, prefix) {
prefix = prefix || '';
var row = Object.keys(data).map(function(key) {
if (typeof data[key] !== 'object') {
return util.format('%s%s="%s"', prefix, key, data[key]);
}
// Flatten this nested object.
return _reformat(data[key], key + '.');
});
return row.join(' ');
} | javascript | {
"resource": ""
} | |
q6496 | Socket | train | function Socket (options) {
this.options = {
port: 80
, secure: false
, document: 'document' in global ? document : false
, resource: 'socket.io'
, transports: io.transports
, 'connect timeout': 10000
, 'try multiple transports': true
, 'reconnect': true
, 're... | javascript | {
"resource": ""
} |
q6497 | train | function (name, callback) {
var self = this;
if (!self.callbacks[name])
self.callbacks[name] = [callback];
else
self.callbacks[name].push(callback);
} | javascript | {
"resource": ""
} | |
q6498 | train | function (data) {
var self = this;
if (typeof data === 'object') {
data = EJSON.stringify(data);
}
_.each(self.callbacks['message'], function (cb) {
cb(data);
});
} | javascript | {
"resource": ""
} | |
q6499 | build | train | function build(config) {
return lazypipe()
.pipe(() => polymerBuild(config))
.pipe(() => addCspCompliance())
.pipe(() => addCacheBusting())
.pipe(() => optimizeAssets())
.pipe(() => injectCustomElementsEs5Adapter());
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.