_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q48500 | createTableLayout | train | function createTableLayout(){
var tableItem = {
type: 'component',
componentName: 'Table'
};
var stackItem = myLayout.root.getItemsById('stack-topleft')[0];
stackItem.addChild(tableItem);
// get focus on the search tab
stackItem.setActiveContentItem(myLayout.root.getItemsById('n... | javascript | {
"resource": ""
} |
q48501 | initJQueryEvents | train | function initJQueryEvents(){
$('#searchDiv').parent().scroll(function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight - 100) {
globalFunc.addNodesInList();
}
});
$('#toggleLayout').click(function() {
toggleLayout();
});
$("#sliderTe... | javascript | {
"resource": ""
} |
q48502 | panToNode | train | function panToNode(node) {
var pos = layout.getNodePosition(node._id);
renderer.moveTo(pos.x, pos.y);
highlightNodeWebGL(node);
} | javascript | {
"resource": ""
} |
q48503 | highlightNodeWebGL | train | function highlightNodeWebGL(node) {
var ui = graphics.getNodeUI(node._id);
if (prevNodeUI){
prevNodeUI.size = NODE_SIZE;
//prevNodeUI.color = hexColorToWebGLColor(colorsByNodeType[node._type]);
}
prevNodeUI = ui;
ui.size = NODE_SIZE * 4;
//ui.color = 0xFFA500FF; //orange
if ... | javascript | {
"resource": ""
} |
q48504 | addToGlobalNodes | train | function addToGlobalNodes(node){
var nodeToAdd = {
"_id": node.id(),
"_world": node.world(),
"_time": node.time(),
"_type": (node.nodeTypeName() ? node.nodeTypeName() : "default")
};
var containsRel = false;
// add all the attributes of the node to the JSON
graph.res... | javascript | {
"resource": ""
} |
q48505 | addNodeToGraph | train | function addNodeToGraph(node){
gNodesDisplayed.push(node);
g.addNode(node._id, node);
if (contains(childrenNodes, node._id)){
var parentNode = getNodeFromId(nodesToBeLinked[node._id].from);
if (contains(gNodesDisplayed, parentNode)){
addLinkToParent(node._id, parentNode._id);
... | javascript | {
"resource": ""
} |
q48506 | addRelToGraph | train | function addRelToGraph(node){
var children = [];
for (var prop in node){
if(node.hasOwnProperty(prop)){
if (typeof node[prop] === 'object') {
var linkedNodes = node[prop];
// same for links
if (colorsByLinkType[prop] == null) {
... | javascript | {
"resource": ""
} |
q48507 | getNodeFromId | train | function getNodeFromId(nodeId){
var res = $.grep(gAllNodes, function(e) {
return e._id === nodeId;
});
return res[0];
} | javascript | {
"resource": ""
} |
q48508 | delayLinkCreation | train | function delayLinkCreation(idParent, idChild, relationName){
childrenNodes.push(idChild);
return {
from: idParent,
name: relationName
};
} | javascript | {
"resource": ""
} |
q48509 | addLinkToParent | train | function addLinkToParent(idNode, idParentNode){
g.addLink(idParentNode, idNode, nodesToBeLinked[idNode].name);
delete nodesToBeLinked[idNode];
//we remove the node from childrenNodes
var index = childrenNodes.indexOf(idNode);
if (index > -1) {
childrenNodes.splice(index, 1);
}
} | javascript | {
"resource": ""
} |
q48510 | toggleLayout | train | function toggleLayout() {
$('.nodeLabel').remove();
isPaused = !isPaused;
if (isPaused) {
$('#toggleLayout').html('<i class="fa fa-play"></i>Resume layout');
renderer.pause();
} else {
$('#toggleLayout').html('<i class="fa fa-pause"></i>Pause layout');
renderer.resume();
... | javascript | {
"resource": ""
} |
q48511 | splitTickText | train | function splitTickText(d, maxWidth) {
var tickText = textFormatted(d),
subtext, spaceIndex, textWidth, splitted = [];
if (Object.prototype.toString.call(tickText) === "[object Array]") {
return tickText;
}
... | javascript | {
"resource": ""
} |
q48512 | createColumnsFromProperties | train | function createColumnsFromProperties(){
var res = [];
for (var i = 0; i < nodeProperties.length; ++i){
var prop = nodeProperties[i];
var obj = {
id: prop,
name: prop,
field: prop
};
res.push(obj);
}
return res;
} | javascript | {
"resource": ""
} |
q48513 | gotMedia | train | function gotMedia(mediaStream) {
// Extract video track.
videoDevice = mediaStream.getVideoTracks()[0];
log('Using camera', videoDevice.label);
const captureDevice = new ImageCapture(videoDevice, mediaStream);
interval = setInterval(function () {
captureDevice.grabFrame().then(processFrame).catch(error =... | javascript | {
"resource": ""
} |
q48514 | findRoutes | train | function findRoutes (dir, fileExtensions) {
let files = fs.readdirSync(dir)
let resolve = f => path.join(dir, f)
let routes = files.filter(f => fileExtensions.indexOf(path.extname(f)) !== -1).map(resolve)
let dirs = files.filter(f => fs.statSync(path.join(dir, f)).isDirectory()).map(resolve)
return routes.con... | javascript | {
"resource": ""
} |
q48515 | scheduleHandler | train | function scheduleHandler (p1, p2) {
return setTimeout(function () {
var x, handler = p1._s ? p2._onFulfilled : p2._onRejected;
// 2.2.7.3
// 2.2.7.4
if (handler === void 0) {
settlePromise(p2, p1._s, p1._v);
return;
}
... | javascript | {
"resource": ""
} |
q48516 | settleWithX | train | function settleWithX (p, x) {
// 2.3.1
if (x === p && x) {
settlePromise(p, $rejected, new TypeError('promise_circular_chain'));
return;
}
// 2.3.2
// 2.3.3
var xthen, type = typeof x;
if (x !== null && (type === 'function' || type === 'ob... | javascript | {
"resource": ""
} |
q48517 | train | function (onNext, onError) {
var self = this, subscriber = new Observable();
subscriber._onNext = onNext;
subscriber._onError = onError;
subscriber._nextErr = genNextErr(subscriber.next);
subscriber.publisher = self;
self.subscribers.push(subscriber);
return sub... | javascript | {
"resource": ""
} | |
q48518 | genScheduler | train | function genScheduler (initQueueSize, fn) {
/**
* All async promise will be scheduled in
* here, so that they can be execute on the next tick.
* @private
*/
var fnQueue = Arr(initQueueSize)
, fnQueueLen = 0;
/**
* Run all queued functions... | javascript | {
"resource": ""
} |
q48519 | flush | train | function flush () {
var i = 0;
while (i < fnQueueLen) {
fn(fnQueue[i], fnQueue[i + 1]);
fnQueue[i++] = $undefined;
fnQueue[i++] = $undefined;
}
fnQueueLen = 0;
if (fnQueue.length > initQueueSize) fnQueue.length ... | javascript | {
"resource": ""
} |
q48520 | settleWithX | train | function settleWithX (p, x) {
// 2.3.1
if (x === p && x) {
settlePromise(p, $rejected, genTypeError($promiseCircularChain));
return p;
}
// 2.3.2
// 2.3.3
if (x !== $null && (isFunction(x) || isObject(x))) {
// 2.3.2.1
var ... | javascript | {
"resource": ""
} |
q48521 | saveUrl | train | function saveUrl(url) {
fs.writeFile('serve-url.log', url, error => {
if (error) {
return console.log(error)
}
console.log('serve-url.log updated!')
})
} | javascript | {
"resource": ""
} |
q48522 | connectionDelay | train | function connectionDelay() {
var delay = self.connectionWait;
if (delay === 0) {
if (self.connectedAt) {
var t = 1000;
var connectedFor = new Date().getTime() - self.connectedAt;
if (connectedFor < t) {
delay = t - connectedFor;
}
}
}... | javascript | {
"resource": ""
} |
q48523 | parseWebSocketEvent | train | function parseWebSocketEvent(event) {
try {
var params = JSON.parse(event.data);
if (typeof params.data === 'string') {
try {
params.data = JSON.parse(params.data);
} catch (e) {
if (!(e instanceof SyntaxError)) {
throw e;
}
... | javascript | {
"resource": ""
} |
q48524 | updateState | train | function updateState(newState, data) {
var prevState = self.state;
self.state = newState;
// Only emit when the state changes
if (prevState !== newState) {
Pusher.debug('State changed', prevState + ' -> ' + newState);
self.emit('state_change', {previous: prevState, current: newS... | javascript | {
"resource": ""
} |
q48525 | Spotify | train | function Spotify () {
if (!(this instanceof Spotify)) return new Spotify();
EventEmitter.call(this);
this.seq = 0;
this.heartbeatInterval = 18E4; // 180s, from "spotify.web.client.js"
this.agent = superagent.agent();
this.connected = false; // true after the WebSocket "connect" message is sent
this._call... | javascript | {
"resource": ""
} |
q48526 | train | function(schema, dontRecurse) {
if ('string' === typeof schema) {
var schemaName = schema.split("#");
schema = schemas.build(schemaName[0], schemaName[1]);
if (!schema)
throw new Error('Could not load schema: ' + schemaName.join('#'));
} else if (schema && !dontRecurse && (!schema.hasO... | javascript | {
"resource": ""
} | |
q48527 | SpotifyError | train | function SpotifyError (err) {
this.domain = err[0] || 0;
this.code = err[1] || 0;
this.description = err[2] || '';
this.data = err[3] || null;
// Error impl
this.name = domains[this.domain];
var msg = codes[this.code];
if (this.description) msg += ' (' + this.description + ')';
this.message = msg;
... | javascript | {
"resource": ""
} |
q48528 | train | function(coords, done) {
var tile = document.createElement("img");
tile.onerror = L.bind(this._tileOnError, this, done, tile);
if (this.options.crossOrigin) {
tile.crossOrigin = "";
}
/*
Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons
http://www.w... | javascript | {
"resource": ""
} | |
q48529 | train | function(coords) {
var zoom = coords.z;
if (this.options.zoomReverse) {
zoom = this.options.maxZoom - zoom;
}
zoom += this.options.zoomOffset;
return L.Util.template(
this._url,
L.extend(
{
r:
this.options.detectRetina &&
L.Browser.retina &&
this.options.maxZoom > 0
... | javascript | {
"resource": ""
} | |
q48530 | train | function(tile, remaining, seedData) {
if (!remaining.length) {
this.fire("seedend", seedData);
return;
}
this.fire("seedprogress", {
bbox: seedData.bbox,
minZoom: seedData.minZoom,
maxZoom: seedData.maxZoom,
queueLength: seedData.queueLength,
remainingLength: remaining.length,
});
var ur... | javascript | {
"resource": ""
} | |
q48531 | train | function(left, right, cost, identifier, allVars, joinVars) {
this.left = left;
this.right = right;
this.cost = cost;
this.i = identifier;
this.vars = allVars;
this.join = joinVars;
} | javascript | {
"resource": ""
} | |
q48532 | train | function(vars, groupVars) {
for(var j=0; j<vars.length; j++) {
var thisVar = "/"+vars[j]+"/";
if(groupVars.indexOf(thisVar) != -1) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} | |
q48533 | train | function(bgp, toJoin, newGroups, newGroupVars) {
var acumGroups = [];
var acumId = "";
var acumVars = "";
for(var gid in toJoin) {
acumId = acumId+gid; // new group id
acumGroups = acumGroups.concat(groups[gid]);
acumVars = acumVars + groupVars[gid]; /... | javascript | {
"resource": ""
} | |
q48534 | train | function (absolute) {
var aPath, bPath, i = 0, j, resultPath = [], result = '';
if (typeof absolute === 'string') {
absolute = $.uri(absolute, {});
}
if (absolute.scheme !== this.scheme ||
absolute.authority !== this.authority) {
return absolute.toString();
}
... | javascript | {
"resource": ""
} | |
q48535 | train | function () {
var result = '';
if (this._string) {
return this._string;
} else {
result = this.scheme === undefined ? result : (result + this.scheme + ':');
result = this.authority === undefined ? result : (result + '//' + this.authority);
result = result + this.path;
... | javascript | {
"resource": ""
} | |
q48536 | train | function (options) {
options = $.extend({ namespaces: this.namespaces, base: this.base }, options || {});
return $.rdf.dump(this.triples(), options);
} | javascript | {
"resource": ""
} | |
q48537 | train | function (triple) {
var binding = {};
binding = testResource(triple.subject, this.subject, binding);
if (binding === null) {
return null;
}
binding = testResource(triple.property, this.property, binding);
if (binding === null) {
return null;
}
binding = te... | javascript | {
"resource": ""
} | |
q48538 | train | function (bindings) {
var t = this;
if (!this.isFixed()) {
t = this.fill(bindings);
}
if (t.isFixed()) {
return $.rdf.triple(t.subject, t.property, t.object, { source: this.toString() });
} else {
return null;
}
} | javascript | {
"resource": ""
} | |
q48539 | train | function(term) {
try {
if(term == null) {
return "";
} if(term.token==='uri') {
return "u"+term.value;
} else if(term.token === 'blank') {
return "b"+term.value;
} else if(term.token === 'literal') {
var l = "l"+term.value;
... | javascript | {
"resource": ""
} | |
q48540 | train | function(filename, charset, callback) {
fs.readFile(filename, function (err, data) {
if (err) throw err;
zlib.gzip(data, function(err, result) {
callback(result);
});
});
} | javascript | {
"resource": ""
} | |
q48541 | train | function(){
if(arguments.length == 1) {
return new Store(arguments[0]);
} else if(arguments.length == 2) {
return new Store(arguments[0], arguments[1]);
} else {
return new Store();
};
} | javascript | {
"resource": ""
} | |
q48542 | train | function (callback) {
return function (new_method, assert_method, arity) {
return function () {
var message = arguments[arity - 1];
var a = exports.assertion({method: new_method, message: message});
try {
assert[assert_method].apply(null, arguments);
... | javascript | {
"resource": ""
} | |
q48543 | train | function (setUp, tearDown, fn) {
return function (test) {
var context = {};
if (tearDown) {
var done = test.done;
test.done = function (err) {
try {
tearDown.call(context, function (err2) {
if (err && err2) {
... | javascript | {
"resource": ""
} | |
q48544 | train | function (setUp, tearDown, group) {
var tests = {};
var keys = _keys(group);
for (var i = 0; i < keys.length; i += 1) {
var k = keys[i];
if (typeof group[k] === 'function') {
tests[k] = wrapTest(setUp, tearDown, group[k]);
}
else if (typeof group[k] === 'object') ... | javascript | {
"resource": ""
} | |
q48545 | convertEntity | train | function convertEntity(entity) {
switch (entity[0]) {
case '"': {
if(entity.indexOf("^^") > 0) {
var parts = entity.split("^^");
return {literal: parts[0] + "^^<" + parts[1] + ">" };
} else {
return { literal: entity };
}
... | javascript | {
"resource": ""
} |
q48546 | coerce | train | function coerce(scopes) {
if (scopes instanceof ScopeSet) {
return scopes;
}
// If we receive a string, assume it's a single scope.
// We deliberately do not attempt to split the string on whitespace here,
// because we want to force callers to explicitly choose between
// exports.fromString() or export... | javascript | {
"resource": ""
} |
q48547 | initialise | train | function initialise (config, log, defaults) {
const { interval, redis: redisConfig } = config;
if (! (interval > 0 && interval < Infinity)) {
throw new TypeError('Invalid interval');
}
if (! log) {
throw new TypeError('Missing log argument');
}
const redis = require('../redis')({
...redisConf... | javascript | {
"resource": ""
} |
q48548 | getIfUtils | train | function getIfUtils(env, vars = ['production', 'prod', 'test', 'development', 'dev']) {
env = typeof env === 'string' ? {[env]: true} : env
if (typeof env !== 'object') {
throw new Error(
`webpack-config-utils:getIfUtils: env passed should be a string/Object. Was ${JSON.stringify(env)}`
)
}
return... | javascript | {
"resource": ""
} |
q48549 | ListCache | train | function ListCache(entries) {
var this$1 = this;
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this$1.set(entry[0], entry[1]);
}
} | javascript | {
"resource": ""
} |
q48550 | findNodeFromPos | train | function findNodeFromPos(pos) {
const lut = this.begins;
assert(is.finitenumber(pos) && pos >= 0);
let left = 0;
let right = lut.length - 1;
while (left < right) {
const mid = Math.floor((left + right) / 2);
assert(mid >= 0 && mid < lut.length);
if (pos > lut[mid].range[0]) ... | javascript | {
"resource": ""
} |
q48551 | replaceNodeWith | train | function replaceNodeWith(node, newNode) {
let done = false;
const parent = node.$parent;
const keys = Object.keys(parent);
keys.forEach(function(key) {
if (parent[key] === node) {
parent[key] = newNode;
done = true;
}
});
if (done) {
return;
}... | javascript | {
"resource": ""
} |
q48552 | _escapeHtml | train | function _escapeHtml (input) {
return String(input)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
} | javascript | {
"resource": ""
} |
q48553 | _list | train | function _list (str, isOrdered) {
if (!str) return str;
var $ = cheerio.load(str);
var listEl = isOrdered ? 'ol' : 'ul';
$(listEl).each(function (i, el) {
var $out = cheerio.load('<p></p>');
var $el = $(el);
$el.find('li').each(function (j, li) {
var tick = isOrdered ? String(j + 1) + '.' :... | javascript | {
"resource": ""
} |
q48554 | sendStats | train | function sendStats() {
var key = req[options.requestKey];
key = key ? key + '.' : '';
// Status Code
var statusCode = res.statusCode || 'unknown_status';
client.increment(key + 'status_code.' + statusCode);
// Response Time
var duration = new Date().getTime() - startTime;
... | javascript | {
"resource": ""
} |
q48555 | Auto | train | function Auto (data, options) {
const converters = { FlatJSON, DSVStr, DSVArr };
const dataFormat = detectDataFormat(data);
if (!dataFormat) {
throw new Error('Couldn\'t detect the data format');
}
return converters[dataFormat](data, options);
} | javascript | {
"resource": ""
} |
q48556 | DSVStr | train | function DSVStr (str, options) {
const defaultOption = {
firstRowHeader: true,
fieldSeparator: ','
};
options = Object.assign({}, defaultOption, options);
const dsv = d3Dsv(options.fieldSeparator);
return DSVArr(dsv.parseRows(str), options);
} | javascript | {
"resource": ""
} |
q48557 | createUnitField | train | function createUnitField(data, schema) {
data = data || [];
let partialField;
switch (schema.type) {
case FieldType.MEASURE:
switch (schema.subtype) {
case MeasureSubtype.CONTINUOUS:
partialField = new PartialField(schema.name, data, schema, new ContinuousParser());
... | javascript | {
"resource": ""
} |
q48558 | generateNestedMap | train | function generateNestedMap(objArray) {
let mainMap = new Map();
objArray.forEach((obj) => {
let params = obj.name.split('.');
let i = 0;
let k = mainMap;
while (k.has(params[i])) {
k = k.get(params[i]);
i++;
}
let kk = new Map();
k... | javascript | {
"resource": ""
} |
q48559 | sum | train | function sum (arr) {
if (isArray(arr) && !(arr[0] instanceof Array)) {
const filteredNumber = getFilteredValues(arr);
const totalSum = filteredNumber.length ?
filteredNumber.reduce((acc, curr) => acc + curr, 0)
: InvalidAwareTypes.NULL;
... | javascript | {
"resource": ""
} |
q48560 | avg | train | function avg (arr) {
if (isArray(arr) && !(arr[0] instanceof Array)) {
const totalSum = sum(arr);
const len = arr.length || 1;
return (Number.isNaN(totalSum) || totalSum instanceof InvalidAwareTypes) ?
InvalidAwareTypes.NULL : totalSum / len;
}
return InvalidAwareTyp... | javascript | {
"resource": ""
} |
q48561 | min | train | function min (arr) {
if (isArray(arr) && !(arr[0] instanceof Array)) {
// Filter out undefined, null and NaN values
const filteredValues = getFilteredValues(arr);
return (filteredValues.length) ? Math.min(...filteredValues) : InvalidAwareTypes.NULL;
}
return InvalidAwareTypes.NULL;
... | javascript | {
"resource": ""
} |
q48562 | variance | train | function variance (arr) {
let mean = avg(arr);
return avg(arr.map(num => (num - mean) ** 2));
} | javascript | {
"resource": ""
} |
q48563 | getSortFn | train | function getSortFn (dataType, sortType, index) {
let retFunc;
switch (dataType) {
case MeasureSubtype.CONTINUOUS:
case DimensionSubtype.TEMPORAL:
if (sortType === 'desc') {
retFunc = (a, b) => b[index] - a[index];
} else {
retFunc = (a, b) => a[index] - b[index];
... | javascript | {
"resource": ""
} |
q48564 | groupData | train | function groupData(data, fieldIndex) {
const hashMap = new Map();
const groupedData = [];
data.forEach((datum) => {
const fieldVal = datum[fieldIndex];
if (hashMap.has(fieldVal)) {
groupedData[hashMap.get(fieldVal)][1].push(datum);
} else {
groupedData.push([... | javascript | {
"resource": ""
} |
q48565 | createSortingFnArg | train | function createSortingFnArg(groupedDatum, targetFields, targetFieldDetails) {
const arg = {
label: groupedDatum[0]
};
targetFields.reduce((acc, next, idx) => {
acc[next] = groupedDatum[1].map(datum => datum[targetFieldDetails[idx].index]);
return acc;
}, arg);
return arg;
} | javascript | {
"resource": ""
} |
q48566 | sortData | train | function sortData(dataObj, sortingDetails) {
const { data, schema } = dataObj;
let fieldName;
let sortMeta;
let fDetails;
let i = sortingDetails.length - 1;
for (; i >= 0; i--) {
fieldName = sortingDetails[i][0];
sortMeta = sortingDetails[i][1];
fDetails = fieldInSchema(... | javascript | {
"resource": ""
} |
q48567 | defSortFn | train | function defSortFn (a, b) {
const a1 = `${a}`;
const b1 = `${b}`;
if (a1 < b1) {
return -1;
}
if (a1 > b1) {
return 1;
}
return 0;
} | javascript | {
"resource": ""
} |
q48568 | merge | train | function merge (arr, lo, mid, hi, sortFn) {
const mainArr = arr;
const auxArr = [];
for (let i = lo; i <= hi; i += 1) {
auxArr[i] = mainArr[i];
}
let a = lo;
let b = mid + 1;
for (let i = lo; i <= hi; i += 1) {
if (a > mid) {
mainArr[i] = auxArr[b];
b... | javascript | {
"resource": ""
} |
q48569 | sort | train | function sort (arr, lo, hi, sortFn) {
if (hi === lo) { return arr; }
const mid = lo + Math.floor((hi - lo) / 2);
sort(arr, lo, mid, sortFn);
sort(arr, mid + 1, hi, sortFn);
merge(arr, lo, mid, hi, sortFn);
return arr;
} | javascript | {
"resource": ""
} |
q48570 | getFieldArr | train | function getFieldArr (dataModel, fieldArr) {
const retArr = [];
const fieldStore = dataModel.getFieldspace();
const dimensions = fieldStore.getDimension();
Object.entries(dimensions).forEach(([key]) => {
if (fieldArr && fieldArr.length) {
if (fieldArr.indexOf(key) !== -1) {
... | javascript | {
"resource": ""
} |
q48571 | getReducerObj | train | function getReducerObj (dataModel, reducers = {}) {
const retObj = {};
const fieldStore = dataModel.getFieldspace();
const measures = fieldStore.getMeasure();
const defReducer = reducerStore.defaultReducer();
Object.keys(measures).forEach((measureName) => {
if (typeof reducers[measureName] ... | javascript | {
"resource": ""
} |
q48572 | groupBy | train | function groupBy (dataModel, fieldArr, reducers, existingDataModel) {
const sFieldArr = getFieldArr(dataModel, fieldArr);
const reducerObj = getReducerObj(dataModel, reducers);
const fieldStore = dataModel.getFieldspace();
const fieldStoreObj = fieldStore.fieldsObj();
const dbName = fieldStore.name;... | javascript | {
"resource": ""
} |
q48573 | FlatJSON | train | function FlatJSON (arr) {
const header = {};
let i = 0;
let insertionIndex;
const columns = [];
const push = columnMajor(columns);
arr.forEach((item) => {
const fields = [];
for (let key in item) {
if (key in header) {
insertionIndex = header[key];
... | javascript | {
"resource": ""
} |
q48574 | prepareSelectionData | train | function prepareSelectionData (fields, i) {
const resp = {};
for (let field of fields) {
resp[field.name()] = new Value(field.partialField.data[i], field);
}
return resp;
} | javascript | {
"resource": ""
} |
q48575 | DSVArr | train | function DSVArr (arr, options) {
const defaultOption = {
firstRowHeader: true,
};
options = Object.assign({}, defaultOption, options);
let header;
const columns = [];
const push = columnMajor(columns);
if (options.firstRowHeader) {
// If header present then mutate the array... | javascript | {
"resource": ""
} |
q48576 | getLanguages | train | function getLanguages(properties) {
if (!Array.isArray(properties['wof:lang_x_official'])) {
return [];
}
return properties['wof:lang_x_official']
.filter(l => (typeof l === 'string' && l.length === 3))
.map(l => l.toLowerCase());
} | javascript | {
"resource": ""
} |
q48577 | concatArrayFields | train | function concatArrayFields(properties, fields){
let arr = [];
fields.forEach(field => {
if (Array.isArray(properties[field]) && properties[field].length) {
arr = arr.concat(properties[field]);
}
});
// dedupe array
return arr.filter((item, pos, self) => self.indexOf(item) === pos);
} | javascript | {
"resource": ""
} |
q48578 | extractDB | train | function extractDB( dbpath ){
let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPlace];
// connect to sql db
let db = new Sqlite3( dbpath, { readonly: true } );
// convert ids to integers and remove any which fail to convert
let cleanIds = targetWofIds.map(id... | javascript | {
"resource": ""
} |
q48579 | findSubdivisions | train | function findSubdivisions( filename ){
// load configuration variables
const config = require('pelias-config').generate(require('../schema')).imports.whosonfirst;
const sqliteDir = path.join(config.datapath, 'sqlite');
let targetWofIds = Array.isArray(config.importPlace) ? config.importPlace: [config.importPla... | javascript | {
"resource": ""
} |
q48580 | setupDocument | train | function setupDocument(record, hierarchy) {
var wofDoc = new Document( 'whosonfirst', record.place_type, record.id );
if (record.name) {
wofDoc.setName('default', record.name);
// index a version of postcode which doesn't contain whitespace
if (record.place_type === 'postalcode' && typeof record.name ... | javascript | {
"resource": ""
} |
q48581 | wofIdToPath | train | function wofIdToPath( id ){
let strId = id.toString();
let parts = [];
while( strId.length ){
let part = strId.substr(0, 3);
parts.push(part);
strId = strId.substr(3);
}
return parts;
} | javascript | {
"resource": ""
} |
q48582 | formatString | train | function formatString (string) {
const separator = "\n";
return Array.isArray(string) ?
string.reduce((acc, line) => acc.concat(line.split(separator)), []) :
string.split(separator);
} | javascript | {
"resource": ""
} |
q48583 | from | train | function from (json) {
const instance = exportableClasses[json.constructor].from(json);
if (json.children) {
instance.add(...json.children.map(child => from(child)));
}
return instance;
} | javascript | {
"resource": ""
} |
q48584 | sanitizeParameters | train | function sanitizeParameters (definition) {
let scalar;
try {
// eslint-disable-next-line no-use-before-define
const vector = Vector.from(definition);
scalar = vector.getDelta();
}
catch (e) {
scalar = definition.getDelta ? definition.getDelta() : definition;
}
ret... | javascript | {
"resource": ""
} |
q48585 | logResponse | train | function logResponse(data, isRejection) {
data = data || {};
// examine the data object
if (data instanceof Error) {
// log the Error object
_this.defaults.error('FAILED: ' + (data.message || 'Unknown Error'), data);
return DSUtils.Promise.reject(data);
... | javascript | {
"resource": ""
} |
q48586 | isClosingHeading | train | function isClosingHeading(node, depth) {
return depth && node && node.type === HEADING && node.depth <= depth
} | javascript | {
"resource": ""
} |
q48587 | pickPrefix | train | function pickPrefix(prefix, object) {
var length = prefix.length;
var sub;
return foldl(
function(acc, val, key) {
if (key.substr(0, length) === prefix) {
sub = key.substr(length);
acc[sub] = val;
}
return acc;
},
{},
object
);
} | javascript | {
"resource": ""
} |
q48588 | normalize | train | function normalize(msg, list) {
var lower = map(function(s) {
return s.toLowerCase();
}, list);
var opts = msg.options || {};
var integrations = opts.integrations || {};
var providers = opts.providers || {};
var context = opts.context || {};
var ret = {};
debug('<-', msg);
// integrations.
each... | javascript | {
"resource": ""
} |
q48589 | convertGeoPoints | train | function convertGeoPoints() {
if (!{}.hasOwnProperty.call(this.schema.__meta, 'geoPointsProps')) {
return;
}
this.schema.__meta.geoPointsProps.forEach((property) => {
if ({}.hasOwnProperty.call(_this.entityData, property)
... | javascript | {
"resource": ""
} |
q48590 | metaData | train | function metaData() {
const meta = {};
Object.keys(schema.paths).forEach((k) => {
switch (schema.paths[k].type) {
case 'geoPoint':
// This allows us to automatically convert valid lng/lat objects
// to Datastore... | javascript | {
"resource": ""
} |
q48591 | applyMethods | train | function applyMethods(entity, schema) {
Object.keys(schema.methods).forEach((method) => {
entity[method] = schema.methods[method];
});
return entity;
} | javascript | {
"resource": ""
} |
q48592 | defaultOptions | train | function defaultOptions(options) {
const optionsDefault = {
validateBeforeSave: true,
explicitOnly: true,
queries: {
readAll: false,
format: queries.formats.JSON,
},
};
options = extend(true, {}, optionsDefault, options);
if (options.joi) {
... | javascript | {
"resource": ""
} |
q48593 | createDataLoader | train | function createDataLoader(ds) {
ds = typeof ds !== 'undefined' ? ds : this && this.ds;
if (!ds) {
throw new Error('A Datastore instance has to be passed');
}
return new DataLoader(keys => (
ds.get(keys).then(([res]) => {
// When providing an Array with 1 Key item, google-da... | javascript | {
"resource": ""
} |
q48594 | train | function (type) {
return function (opts) {
var opt = opts || {};
var userAttrs = getUserAttrs(opt);
var w = {
classes: opt.classes,
type: type,
formatValue: function (value) {
return (value || value === 0) ? value : null;
}
... | javascript | {
"resource": ""
} | |
q48595 | sendRequestsSync | train | function sendRequestsSync(requests) {
// only try to require optional dependency netlinkwrapper once
if (!netLinkHasBeenRequired) {
netLinkHasBeenRequired = true;
try {
netLink = require('netlinkwrapper')();
} catch (requireNetlinkError) {
logger.warn(
'Failed to require optional dep... | javascript | {
"resource": ""
} |
q48596 | sendHttpPostRequestSync | train | function sendHttpPostRequestSync(port, path, data) {
logger.debug({ payload: data }, 'Sending payload synchronously to %s', path);
try {
var payload = JSON.stringify(data);
var payloadLength = buffer.fromString(payload, 'utf8').length;
} catch (payloadSerializationError) {
logger.warn('Could not seria... | javascript | {
"resource": ""
} |
q48597 | instrument | train | function instrument(build) {
if (typeof build !== 'function') {
return build;
}
// copy further exported properties
Object.keys(build).forEach(function(k) {
overwrittenBuild[k] = build[k];
});
return overwrittenBuild;
function overwrittenBuild() {
var app = build.apply(this, arguments);
... | javascript | {
"resource": ""
} |
q48598 | makePromise | train | function makePromise(requestInstance, promiseFactoryFn) {
// Resolver function wich assigns the promise (resolve, reject) functions
// to the requestInstance
function Resolver(resolve, reject) {
this._resolve = resolve;
this._reject = reject;
}
return promiseFactoryFn(Resolver.bind(requestInstance))... | javascript | {
"resource": ""
} |
q48599 | makeHelper | train | function makeHelper(obj, verb) {
obj[verb] = function helper(url, options, f) {
// ('url')
if(_.isString(url)){
// ('url', f)
if(_.isFunction(options)){
f = options;
}
if(!_.isObject(options)){
options = {};
}
// ('url', {object})
options.url = url;
... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.