_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q28800 | train | function(name, params, callback) {
// If we get (name, callback) instead of (name, params, callback)
// do the necessary variable swap
if (utils.isFunction(params) && !callback) {
callback = params;
params = {};
}
params = para... | javascript | {
"resource": ""
} | |
q28801 | train | function(callback) {
callback = callback || function() {};
var that = this;
var params = {
count: this._pagesize,
offset: this._offset
};
return this._endpoint(params, function(err, results) {
if (er... | javascript | {
"resource": ""
} | |
q28802 | EventWriter | train | function EventWriter(output, error) {
this._out = utils.isUndefined(output) ? process.stdout : output;
this._err = utils.isUndefined(error) ? process.stderr : error;
// Has the opening <stream> tag been written yet?
this._headerWritten = false;
} | javascript | {
"resource": ""
} |
q28803 | Scheme | train | function Scheme(title) {
this.title = utils.isUndefined(title) ? "" : title;
// Set the defaults.
this.description = null;
this.useExternalValidation = true;
this.useSingleInstance = false;
this.streamingMode = Scheme.streamingModeXML;
// List of Argument object... | javascript | {
"resource": ""
} |
q28804 | stringifyArray | train | function stringifyArray(arr, prefix) {
var ret = [];
if (!prefix) throw new TypeError('stringify expects an object');
for (var i = 0; i < arr.length; i++) {
ret.push(stringify(arr[i], prefix + '[]'));
}
return ret.join('&');
} | javascript | {
"resource": ""
} |
q28805 | lastBraceInKey | train | function lastBraceInKey(str) {
var len = str.length
, brace
, c;
for (var i = 0; i < len; ++i) {
c = str[i];
if (']' == c) brace = false;
if ('[' == c) brace = true;
if ('=' == c && !brace) return i;
}
} | javascript | {
"resource": ""
} |
q28806 | train | function(a, b) {
c = this;
if (!b) {
return c.options[a];
} else {
c._u(a, b);
}
} | javascript | {
"resource": ""
} | |
q28807 | train | function( a, b ) {
this.id = b.attr('id');
this.instances = [];
this.element = b;
this.options = jQuery.extend(this.options, a);
this._create();
if ( this._init ) {
this._init();
}
} | javascript | {
"resource": ""
} | |
q28808 | train | function(a, b) {
var map = this.get('map');
jQuery.extend(this.options, { 'center': map.getCenter(), 'mapTypeId': map.getMapTypeId(), 'zoom': map.getZoom() } );
if (a && b) {
this.options[a] = b;
}
map.setOptions(this.options);
// ... | javascript | {
"resource": ""
} | |
q28809 | train | function(a) {
this.get('bounds', new google.maps.LatLngBounds()).extend(this._latLng(a));
this.get('map').fitBounds(this.get('bounds'));
} | javascript | {
"resource": ""
} | |
q28810 | train | function(a, b, c) {
var d = this.get('map');
var c = c || google.maps.Marker;
a.position = (a.position) ? this._latLng(a.position) : null;
var e = new c( jQuery.extend({'map': d, 'bounds': false}, a) );
var f = this.get('markers', []);
if ( e.id ) ... | javascript | {
"resource": ""
} | |
q28811 | train | function(a, b) {
var c = new google.maps.InfoWindow(a);
this._call(b, c);
return $(c);
} | javascript | {
"resource": ""
} | |
q28812 | train | function(a, b) {
var c = this.instances[this.id];
if (!c[a]) {
if ( a.indexOf('>') > -1 ) {
var e = a.replace(/ /g, '').split('>');
for ( var i = 0; i < e.length; i++ ) {
if ( !c[e[i]] ) {
... | javascript | {
"resource": ""
} | |
q28813 | train | function(a, b) {
this.get('iw', new google.maps.InfoWindow).setOptions(a);
this.get('iw').open(this.get('map'), this._unwrap(b));
} | javascript | {
"resource": ""
} | |
q28814 | train | function() {
this.clear('markers');
this.clear('services');
this.clear('overlays');
var a = this.instances[this.id];
for ( b in a ) {
a[b] = null;
}
} | javascript | {
"resource": ""
} | |
q28815 | train | function(a) {
if ( $.isFunction(a) ) {
a.apply(this, Array.prototype.slice.call(arguments, 1));
}
} | javascript | {
"resource": ""
} | |
q28816 | train | function(a) {
if ( a instanceof google.maps.LatLng ) {
return a;
} else {
var b = a.replace(/ /g,'').split(',');
return new google.maps.LatLng(b[0], b[1]);
}
} | javascript | {
"resource": ""
} | |
q28817 | train | function(sourceDir, newDirLocation, opts) {
if (!opts || !opts.preserve) {
try {
if(fs.statSync(newDirLocation).isDirectory()) {
exports.rmdirSyncRecursive(newDirLocation);
}
}
catch(e) { }
}
/* Create the... | javascript | {
"resource": ""
} | |
q28818 | train | function(job, done) {
Async.whilst(
function() { return !job.properties().isDone; },
function(iterationDone) {
job.fetch(function(err, job) {
if (err) {
cal... | javascript | {
"resource": ""
} | |
q28819 | train | function(results) {
for(var i = 0; i < results.rows.length; i++) {
console.log("Result " + (i + 1) + ": ");
var row = results.rows[i];
for(var j = 0; j < results.fields.length; j++) {
var field = results.fields[j];
var value = row[j];
... | javascript | {
"resource": ""
} | |
q28820 | train | function(results) {
var rows = [];
var cols = results.columns;
var mapFirst = function(col) { return col.shift(); };
while(cols.length > 0 && cols[0].length > 0) {
rows.push(cols.map(mapFirst));
}
results.rows = rows;
retu... | javascript | {
"resource": ""
} | |
q28821 | train | function(results) {
if (results) {
var isRows = !!results.rows;
var numResults = (results.rows ? results.rows.length : (results.columns[0] || []).length);
console.log("====== " + numResults + " RESULTS (preview: " + !!results.preview + ") ======");
... | javascript | {
"resource": ""
} | |
q28822 | train | function(params, extra) {
var output = [params];
if(extra != undefined) {
output.push(extra);
}
else {
output.push(null);
}
return {
start: function(completeCallback, errorCallback, messageCallback) {
completeCallback = completeCallback || function() {};
errorCallback = errorCallback... | javascript | {
"resource": ""
} | |
q28823 | render | train | function render(source, config, options) {
config = config || {};
config.raml2HtmlVersion = pjson.version;
// Check if option is old boolean `validation` to keep backward compatibility
if (typeof options === 'boolean') {
options = {
validate: options,
};
}
if (options === undefined) {
op... | javascript | {
"resource": ""
} |
q28824 | getPlistFilenames | train | function getPlistFilenames(xcode) {
return unique(
flattenDeep(
xcode.document.projects.map(project => {
return project.targets.filter(Boolean).map(target => {
return target.buildConfigurationsList.buildConfigurations.map(
config => {
return config.ast.value.get("buildSettings").get("INFOPLI... | javascript | {
"resource": ""
} |
q28825 | isExpoProject | train | function isExpoProject(projPath) {
try {
let module = resolveFrom(projPath, "expo");
let appInfo = require(`${projPath}/app.json`);
return !!(module && appInfo.expo);
} catch (err) {
return false;
}
} | javascript | {
"resource": ""
} |
q28826 | log | train | function log(msg, silent) {
if (!silent) {
console.log("[RNV]", chalk[msg.style || "reset"](msg.text));
}
} | javascript | {
"resource": ""
} |
q28827 | Quat2Angle | train | function Quat2Angle(x, y, z, w) {
const test = x * y + z * w;
// singularity at north pole
if (test > 0.499) {
const yaw = 2 * Math.atan2(x, w);
const pitch = Math.PI / 2;
const roll = 0;
return new THREE.Vector3(pitch, roll, yaw);
}
// singularity at south pole
if (test < -0.499) {
c... | javascript | {
"resource": ""
} |
q28828 | toCodePoint | train | function toCodePoint(input, separator = "-") {
const codePoints = [];
for (let codePoint of input) {
codePoints.push(codePoint.codePointAt(0).toString(16));
}
return codePoints.join(separator);
} | javascript | {
"resource": ""
} |
q28829 | registerFilters | train | function registerFilters (filters) {
if (isArray(filters)) {
lazyStringFilters = lazyStringFilters.concat(filters)
} else if (isObject(filters)) {
Object.keys(filters).forEach(name => {
addFilter(name, filters[name])
})
}
} | javascript | {
"resource": ""
} |
q28830 | getMarkup | train | function getMarkup(webserver, provider) {
var markup = renderToString(provider),
styles = "";
if (process.env.NODE_ENV === "production") {
styles = `<link href="${webserver}/dist/main.css" rel="stylesheet"></link>`;
}
return `<!doctype html>
<html>
<head>
... | javascript | {
"resource": ""
} |
q28831 | takePhoto | train | function takePhoto () {
let sizeFactor = 1;
let imageType = IMAGE_TYPES.JPG;
let imageCompression = 1;
let config = {
sizeFactor,
imageType,
imageCompression
};
let dataUri = cameraPhoto.getDataUri(config);
imgElement.src = dataUri;
} | javascript | {
"resource": ""
} |
q28832 | train | function () {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
console.log("Connecting local");
return new Promise(function (resolve, reject) {
exports.bs_local = new browserstack.Local();
exports.bs_local.start({'key': exports.config.capabilities['browserstack.key']}... | javascript | {
"resource": ""
} | |
q28833 | relayEvents | train | function relayEvents(listener, emitter, events) {
events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event)));
} | javascript | {
"resource": ""
} |
q28834 | retrieveEJSON | train | function retrieveEJSON() {
let EJSON = null;
try {
EJSON = requireOptional('mongodb-extjson');
} catch (error) {} // eslint-disable-line
if (!EJSON) {
EJSON = {
parse: noEJSONError,
deserialize: noEJSONError,
serialize: noEJSONError,
stringify: noEJSONError,
setBSONModule: ... | javascript | {
"resource": ""
} |
q28835 | maxWireVersion | train | function maxWireVersion(topologyOrServer) {
if (topologyOrServer.ismaster) {
return topologyOrServer.ismaster.maxWireVersion;
}
if (topologyOrServer.description) {
return topologyOrServer.description.maxWireVersion;
}
return null;
} | javascript | {
"resource": ""
} |
q28836 | writableServerSelector | train | function writableServerSelector() {
return function(topologyDescription, servers) {
return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable));
};
} | javascript | {
"resource": ""
} |
q28837 | tagSetMatch | train | function tagSetMatch(tagSet, serverTags) {
const keys = Object.keys(tagSet);
const serverTagKeys = Object.keys(serverTags);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) {
return false;
}
}
return true;... | javascript | {
"resource": ""
} |
q28838 | tagSetReducer | train | function tagSetReducer(readPreference, servers) {
if (
readPreference.tags == null ||
(Array.isArray(readPreference.tags) && readPreference.tags.length === 0)
) {
return servers;
}
for (let i = 0; i < readPreference.tags.length; ++i) {
const tagSet = readPreference.tags[i];
const serversMat... | javascript | {
"resource": ""
} |
q28839 | defaultAuthProviders | train | function defaultAuthProviders(bson) {
return {
mongocr: new MongoCR(bson),
x509: new X509(bson),
plain: new Plain(bson),
gssapi: new GSSAPI(bson),
sspi: new SSPI(bson),
'scram-sha-1': new ScramSHA1(bson),
'scram-sha-256': new ScramSHA256(bson)
};
} | javascript | {
"resource": ""
} |
q28840 | canCompress | train | function canCompress(command) {
const commandDoc = command instanceof Msg ? command.command : command.query;
const commandName = Object.keys(commandDoc)[0];
return uncompressibleCommands.indexOf(commandName) === -1;
} | javascript | {
"resource": ""
} |
q28841 | remove | train | function remove(connection, connections) {
for (var i = 0; i < connections.length; i++) {
if (connections[i] === connection) {
connections.splice(i, 1);
return true;
}
}
} | javascript | {
"resource": ""
} |
q28842 | retrieveSnappy | train | function retrieveSnappy() {
var snappy = null;
try {
snappy = require_optional('snappy');
} catch (error) {} // eslint-disable-line
if (!snappy) {
snappy = {
compress: noSnappyWarning,
uncompress: noSnappyWarning,
compressSync: noSnappyWarning,
uncompressSync: noSnappyWarning
... | javascript | {
"resource": ""
} |
q28843 | matchesParentDomain | train | function matchesParentDomain(srvAddress, parentDomain) {
const regex = /^.*?\./;
const srv = `.${srvAddress.replace(regex, '')}`;
const parent = `.${parentDomain.replace(regex, '')}`;
return srv.endsWith(parent);
} | javascript | {
"resource": ""
} |
q28844 | parseSrvConnectionString | train | function parseSrvConnectionString(uri, options, callback) {
const result = URL.parse(uri, true);
if (result.hostname.split('.').length < 3) {
return callback(new MongoParseError('URI does not have hostname, domain name and tld'));
}
result.domainLength = result.hostname.split('.').length;
if (result.pat... | javascript | {
"resource": ""
} |
q28845 | parseQueryStringItemValue | train | function parseQueryStringItemValue(key, value) {
if (Array.isArray(value)) {
// deduplicate and simplify arrays
value = value.filter((v, idx) => value.indexOf(v) === idx);
if (value.length === 1) value = value[0];
} else if (value.indexOf(':') > 0) {
value = value.split(',').reduce((result, pair) =>... | javascript | {
"resource": ""
} |
q28846 | applyConnectionStringOption | train | function applyConnectionStringOption(obj, key, value, options) {
// simple key translation
if (key === 'journal') {
key = 'j';
} else if (key === 'wtimeoutms') {
key = 'wtimeout';
}
// more complicated translation
if (BOOLEAN_OPTIONS.has(key)) {
value = value === 'true' || value === true;
} e... | javascript | {
"resource": ""
} |
q28847 | applyAuthExpectations | train | function applyAuthExpectations(parsed) {
if (parsed.options == null) {
return;
}
const options = parsed.options;
const authSource = options.authsource || options.authSource;
if (authSource != null) {
parsed.auth = Object.assign({}, parsed.auth, { db: authSource });
}
const authMechanism = option... | javascript | {
"resource": ""
} |
q28848 | checkTLSOptions | train | function checkTLSOptions(queryString) {
const queryStringKeys = Object.keys(queryString);
if (
queryStringKeys.indexOf('tlsInsecure') !== -1 &&
(queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 ||
queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1)
) {
throw new MongoParseEr... | javascript | {
"resource": ""
} |
q28849 | train | function(self, server, cb) {
// Measure running time
var start = new Date().getTime();
// Emit the server heartbeat start
emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name });
// Execute ismaster
// Set the socketTimeout for a monitoring message to a low number
// Ensuring ismast... | javascript | {
"resource": ""
} | |
q28850 | train | function(host, self, options) {
// If this is not the initial scan
// Is this server already being monitoried, then skip monitoring
if (!options.haInterval) {
for (var i = 0; i < self.intervalIds.length; i++) {
if (self.intervalIds[i].__host === host) {
return;
}
}
}
// Get the ha... | javascript | {
"resource": ""
} | |
q28851 | executeReconnect | train | function executeReconnect(self) {
return function() {
if (self.state === DESTROYED || self.state === UNREFERENCED) {
return;
}
connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
var monitoringFrequencey = self.s.replicaSetState.hasPrimary()
? _ha... | javascript | {
"resource": ""
} |
q28852 | emitSDAMEvent | train | function emitSDAMEvent(self, event, description) {
if (self.listeners(event).length > 0) {
self.emit(event, description);
}
} | javascript | {
"resource": ""
} |
q28853 | executeWriteOperation | train | function executeWriteOperation(args, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// TODO: once we drop Node 4, use destructuring either here or in arguments.
const self = args.self;
const op = args.op;
const ns = args.ns;
const op... | javascript | {
"resource": ""
} |
q28854 | xor | train | function xor(a, b) {
if (!Buffer.isBuffer(a)) a = Buffer.from(a);
if (!Buffer.isBuffer(b)) b = Buffer.from(b);
const length = Math.max(a.length, b.length);
const res = [];
for (let i = 0; i < length; i += 1) {
res.push(a[i] ^ b[i]);
}
return Buffer.from(res).toString('base64');
} | javascript | {
"resource": ""
} |
q28855 | isRetryableError | train | function isRetryableError(error) {
return (
RETRYABLE_ERROR_CODES.has(error.code) ||
error instanceof MongoNetworkError ||
error.message.match(/not master/) ||
error.message.match(/node is recovering/)
);
} | javascript | {
"resource": ""
} |
q28856 | parseServerType | train | function parseServerType(ismaster) {
if (!ismaster || !ismaster.ok) {
return ServerType.Unknown;
}
if (ismaster.isreplicaset) {
return ServerType.RSGhost;
}
if (ismaster.msg && ismaster.msg === 'isdbgrid') {
return ServerType.Mongos;
}
if (ismaster.setName) {
if (ismaster.hidden) {
... | javascript | {
"resource": ""
} |
q28857 | destroyServer | train | function destroyServer(server, topology, callback) {
LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event));
server.destroy(() => {
topology.emit(
'serverClosed',
new monitoring.ServerClosedEvent(topology.s.id, server.description.address)
);
if (typeof callback === 'functio... | javascript | {
"resource": ""
} |
q28858 | parseStringSeedlist | train | function parseStringSeedlist(seedlist) {
return seedlist.split(',').map(seed => ({
host: seed.split(':')[0],
port: seed.split(':')[1] || 27017
}));
} | javascript | {
"resource": ""
} |
q28859 | resetServerState | train | function resetServerState(server, error, options) {
options = Object.assign({}, { clearPool: false }, options);
function resetState() {
server.emit(
'descriptionReceived',
new ServerDescription(server.description.address, null, { error })
);
}
if (options.clearPool && server.pool) {
se... | javascript | {
"resource": ""
} |
q28860 | train | function(seedlist, options) {
options = options || {};
// Get replSet Id
this.id = id++;
// Internal state
this.s = {
options: Object.assign({}, options),
// BSON instance
bson:
options.bson ||
new BSON([
BSON.Binary,
BSON.Code,
BSON.DBRef,
BSON.Decima... | javascript | {
"resource": ""
} | |
q28861 | pingServer | train | function pingServer(_self, _server, cb) {
// Measure running time
var start = new Date().getTime();
// Emit the server heartbeat start
emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name });
// Execute ismaster
_server.command(
'admin.$cmd',
{... | javascript | {
"resource": ""
} |
q28862 | resolveClusterTime | train | function resolveClusterTime(topology, $clusterTime) {
if (topology.clusterTime == null) {
topology.clusterTime = $clusterTime;
} else {
if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) {
topology.clusterTime = $clusterTime;
}
}
} | javascript | {
"resource": ""
} |
q28863 | train | function(topology) {
const maxWireVersion = topology.lastIsMaster().maxWireVersion;
if (maxWireVersion < RETRYABLE_WIRE_VERSION) {
return false;
}
if (!topology.logicalSessionTimeoutMinutes) {
return false;
}
if (topologyType(topology) === TopologyType.Single) {
return false;
}
return tru... | javascript | {
"resource": ""
} | |
q28864 | train | function(readPreference, servers) {
if (readPreference.tags == null) return servers;
var filteredServers = [];
var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags];
// Iterate over the tags
for (var j = 0; j < tagsArray.length; j++) {
var tags = tagsArray[j];
... | javascript | {
"resource": ""
} | |
q28865 | train | function(options) {
options = options || {};
// Add event listener
EventEmitter.call(this);
// Server instance id
this.id = id++;
// Internal state
this.s = {
// Options
options: options,
// Logger
logger: Logger('Server', options),
// Factory overrides
Cursor: options.cursorFac... | javascript | {
"resource": ""
} | |
q28866 | train | function(message) {
return {
length: message.readInt32LE(0),
requestId: message.readInt32LE(4),
responseTo: message.readInt32LE(8),
opCode: message.readInt32LE(12)
};
} | javascript | {
"resource": ""
} | |
q28867 | TCPConnection | train | function TCPConnection(user) {
this.user = user;
// Pick a CM randomly
if (!user._cmList || !user._cmList.tcp_servers) {
throw new Error("Nothing to connect to: " + (user._cmList ? "no TCP server list" : "no CM list"));
}
let tcpCm = user._cmList.tcp_servers[Math.floor(Math.random() * user._cmList.tcp_servers.... | javascript | {
"resource": ""
} |
q28868 | toChatID | train | function toChatID(steamID) {
steamID = Helpers.steamID(steamID);
if (steamID.type == SteamID.Type.CLAN) {
steamID.type = SteamID.Type.CHAT;
steamID.instance |= SteamID.ChatInstanceFlags.Clan;
}
return steamID;
} | javascript | {
"resource": ""
} |
q28869 | fromChatID | train | function fromChatID(steamID) {
steamID = Helpers.steamID(steamID);
if (steamID.isGroupChat()) {
steamID.type = SteamID.Type.CLAN;
steamID.instance &= ~SteamID.ChatInstanceFlags.Clan;
}
return steamID;
} | javascript | {
"resource": ""
} |
q28870 | decomposeChatFlags | train | function decomposeChatFlags(chat, chatFlags) {
chat.private = !!(chatFlags & SteamUser.EChatFlags.Locked);
chat.invisibleToFriends = !!(chatFlags & SteamUser.EChatFlags.InvisibleToFriends);
chat.officersOnlyChat = !!(chatFlags & SteamUser.EChatFlags.Moderated);
chat.unjoinable = !!(chatFlags & SteamUser.EChatFlags.... | javascript | {
"resource": ""
} |
q28871 | processChatRoomSummaryPair | train | function processChatRoomSummaryPair(summaryPair, preProcessed) {
if (!preProcessed) {
summaryPair = preProcessObject(summaryPair);
}
summaryPair.group_state = processUserChatGroupState(summaryPair.user_chat_group_state, true);
summaryPair.group_summary = processChatGroupSummary(summaryPair.group_summary, true);
... | javascript | {
"resource": ""
} |
q28872 | processChatGroupSummary | train | function processChatGroupSummary(groupSummary, preProcessed) {
if (!preProcessed) {
groupSummary = preProcessObject(groupSummary);
}
if (groupSummary.top_members) {
groupSummary.top_members = groupSummary.top_members.map(accountid => SteamID.fromIndividualAccountID(accountid));
}
return groupSummary;
} | javascript | {
"resource": ""
} |
q28873 | preProcessObject | train | function preProcessObject(obj) {
for (let key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
let val = obj[key];
if (key.match(/^steamid_/) && typeof val === 'string' && val != '0') {
obj[key] = new SteamID(val.toString());
} else if (key == 'timestamp' || key.match(/^time_/) || key.match(/_tim... | javascript | {
"resource": ""
} |
q28874 | extractFonts | train | function extractFonts (state) {
var list = String(state.list.buffer).split(',')
var res = list.filter(function (font) {
var extname = path.extname(font)
return extname === '.woff' ||
extname === '.woff2' ||
extname === '.eot' ||
extname === '.ttf'
})
return res
} | javascript | {
"resource": ""
} |
q28875 | init | train | function init (dirname, done) {
dirname = path.join(basedir, dirname)
fs.access(dirname, function (err) {
if (err) return done()
readdir(dirname, function (err, _list) {
if (err) return done(err)
list = list.concat(_list)
done()
})
})
} | javascript | {
"resource": ""
} |
q28876 | matchSorter | train | function matchSorter(items, value, options = {}) {
// not performing any search/sort if value(search term) is empty
if (!value) return items
const {keys, threshold = rankings.MATCHES} = options
const matchedItems = items.reduce(reduceItemsToRanked, [])
return matchedItems.sort(sortRankedItems).map(({item}) =... | javascript | {
"resource": ""
} |
q28877 | getHighestRanking | train | function getHighestRanking(item, keys, value, options) {
if (!keys) {
return {
rank: getMatchRanking(item, value, options),
keyIndex: -1,
keyThreshold: options.threshold,
}
}
const valuesToRank = getAllValuesToRank(item, keys)
return valuesToRank.reduce(
({rank, keyIndex, keyThresh... | javascript | {
"resource": ""
} |
q28878 | getMatchRanking | train | function getMatchRanking(testString, stringToRank, options) {
/* eslint complexity:[2, 12] */
testString = prepareValueForComparison(testString, options)
stringToRank = prepareValueForComparison(stringToRank, options)
// too long
if (stringToRank.length > testString.length) {
return rankings.NO_MATCH
}... | javascript | {
"resource": ""
} |
q28879 | getCaseRanking | train | function getCaseRanking(testString) {
const containsUpperCase = testString.toLowerCase() !== testString
const containsDash = testString.indexOf('-') >= 0
const containsUnderscore = testString.indexOf('_') >= 0
if (!containsUpperCase && !containsUnderscore && containsDash) {
return caseRankings.KEBAB
}
... | javascript | {
"resource": ""
} |
q28880 | isCaseAcronym | train | function isCaseAcronym(testString, stringToRank, caseRank) {
let splitValue = null
switch (caseRank) {
case caseRankings.SNAKE:
splitValue = '_'
break
case caseRankings.KEBAB:
splitValue = '-'
break
case caseRankings.PASCAL:
case caseRankings.CAMEL:
splitValue = /(?=[A-... | javascript | {
"resource": ""
} |
q28881 | getClosenessRanking | train | function getClosenessRanking(testString, stringToRank) {
let charNumber = 0
function findMatchingCharacter(matchChar, string, index) {
for (let j = index; j < string.length; j++) {
const stringChar = string[j]
if (stringChar === matchChar) {
return j + 1
}
}
return -1
}
fun... | javascript | {
"resource": ""
} |
q28882 | sortRankedItems | train | function sortRankedItems(a, b) {
const aFirst = -1
const bFirst = 1
const {rank: aRank, index: aIndex, keyIndex: aKeyIndex} = a
const {rank: bRank, index: bIndex, keyIndex: bKeyIndex} = b
const same = aRank === bRank
if (same) {
if (aKeyIndex === bKeyIndex) {
return aIndex < bIndex ? aFirst : bFir... | javascript | {
"resource": ""
} |
q28883 | getItemValues | train | function getItemValues(item, key) {
if (typeof key === 'object') {
key = key.key
}
let value
if (typeof key === 'function') {
value = key(item)
// eslint-disable-next-line no-negated-condition
} else if (key.indexOf('.') !== -1) {
// handle nested keys
value = key
.split('.')
.... | javascript | {
"resource": ""
} |
q28884 | getAllValuesToRank | train | function getAllValuesToRank(item, keys) {
return keys.reduce((allVals, key) => {
const values = getItemValues(item, key)
if (values) {
values.forEach(itemValue => {
allVals.push({
itemValue,
attributes: getKeyAttributes(key),
})
})
}
return allVals
}, ... | javascript | {
"resource": ""
} |
q28885 | getKeyAttributes | train | function getKeyAttributes(key) {
if (typeof key === 'string') {
key = {key}
}
return {
maxRanking: Infinity,
minRanking: -Infinity,
...key,
}
} | javascript | {
"resource": ""
} |
q28886 | sqSegBoxDist | train | function sqSegBoxDist(a, b, bbox) {
if (inside(a, bbox) || inside(b, bbox)) return 0;
var d1 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.maxX, bbox.minY);
if (d1 === 0) return 0;
var d2 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.minX, bbox.maxY);
if (d2 =... | javascript | {
"resource": ""
} |
q28887 | updateBBox | train | function updateBBox(node) {
var p1 = node.p;
var p2 = node.next.p;
node.minX = Math.min(p1[0], p2[0]);
node.minY = Math.min(p1[1], p2[1]);
node.maxX = Math.max(p1[0], p2[0]);
node.maxY = Math.max(p1[1], p2[1]);
return node;
} | javascript | {
"resource": ""
} |
q28888 | fastConvexHull | train | function fastConvexHull(points) {
var left = points[0];
var top = points[0];
var right = points[0];
var bottom = points[0];
// find the leftmost, rightmost, topmost and bottommost points
for (var i = 0; i < points.length; i++) {
var p = points[i];
if (p[0] < left[0]) left = p;
... | javascript | {
"resource": ""
} |
q28889 | insertNode | train | function insertNode(p, prev) {
var node = {
p: p,
prev: null,
next: null,
minX: 0,
minY: 0,
maxX: 0,
maxY: 0
};
if (!prev) {
node.prev = node;
node.next = node;
} else {
node.next = prev.next;
node.prev = prev;
... | javascript | {
"resource": ""
} |
q28890 | getSqDist | train | function getSqDist(p1, p2) {
var dx = p1[0] - p2[0],
dy = p1[1] - p2[1];
return dx * dx + dy * dy;
} | javascript | {
"resource": ""
} |
q28891 | Snapshot | train | function Snapshot (id, obj) {
if (!id) {
var errIdMsg = 'id not injected!';
debug(errIdMsg);
throw new Error(errIdMsg);
}
if (!obj) {
var errObjMsg = 'object not injected!';
debug(errObjMsg);
throw new Error(errObjMsg);
}
if (!obj.aggregateId) {
var errAggIdMsg = 'object.aggregat... | javascript | {
"resource": ""
} |
q28892 | EventStream | train | function EventStream (eventstore, query, events) {
if (!eventstore) {
var errESMsg = 'eventstore not injected!';
debug(errESMsg);
throw new Error(errESMsg);
}
if (typeof eventstore.commit !== 'function') {
var errESfnMsg = 'eventstore.commit not injected!';
debug(errESfnMsg);
throw new Er... | javascript | {
"resource": ""
} |
q28893 | train | function() {
for (var i = 0, len = this.events.length; i < len; i++) {
if (this.events[i].streamRevision > this.lastRevision) {
this.lastRevision = this.events[i].streamRevision;
}
}
return this.lastRevision;
} | javascript | {
"resource": ""
} | |
q28894 | train | function(events) {
if (!_.isArray(events)) {
var errEvtsArrMsg = 'events should be an array!';
debug(errEvtsArrMsg);
throw new Error(errEvtsArrMsg);
}
var self = this;
_.each(events, function(evt) {
self.addEvent(evt);
});
} | javascript | {
"resource": ""
} | |
q28895 | trigger | train | function trigger (dispatcher) {
var queue = dispatcher.undispatchedEventsQueue || []
var event;
// if the last loop is still in progress leave this loop
if (dispatcher.isRunning) return;
dispatcher.isRunning = true;
(function next (e) {
// dipatch one event in queue and call the _next_ callback, whi... | javascript | {
"resource": ""
} |
q28896 | process | train | function process (event, nxt) {
// Publish it now...
debug('publish event...');
dispatcher.publisher(event.payload, function(err) {
if (err) {
return debug(err);
}
// ...and set the published event to dispatched.
debug('set event to dispatched...');
d... | javascript | {
"resource": ""
} |
q28897 | train | function(events) {
var self = this;
events.forEach(function(event) {
self.undispatchedEventsQueue.push(event);
});
trigger(this);
} | javascript | {
"resource": ""
} | |
q28898 | train | function(callback) {
if (typeof this.publisher !== 'function') {
var pubErrMsg = 'publisher not injected!';
debug(pubErrMsg);
if (callback) callback(new Error(pubErrMsg));
return;
}
if (!this.store || typeof this.store.getUndispatchedEvents !== 'function'
|| typ... | javascript | {
"resource": ""
} | |
q28899 | train | function (fn) {
if (fn.length === 1) {
fn = _.wrap(fn, function(func, evt, callback) {
func(evt);
callback(null);
});
}
this.publisher = fn;
return this;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.