_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22900
|
runStep
|
train
|
function runStep(step)
{
switch (step) {
case 1 :
trace("-- Beginning benchmark --");
initializeDB();
initializeUnique();
setTimeout(function() { runStep(2); }, 100);
break;
case 2 :
benchGet();
setTimeout(function() { runStep(3); }, 100);
break;
case 3 :
benchUniquePerf();
setTimeout(function() { runStep(4); }, 100);
trace("");
trace("-- Benchmarking query on non-indexed column --");
break;
case 4 :
benchFind(); // find benchmark on unindexed customid field
setTimeout(function() { runStep(5); }, 100);
break;
case 5 :
benchRS(); // resultset find benchmark on unindexed customid field
setTimeout(function() { runStep(6); }, 100);
break;
case 6 :
benchDV();
setTimeout(function() { runStep(7); }, 100);
trace("");
trace("-- Adding Binary Index to query column and repeating benchmarks --");
break;
case 7 :
samplecoll.ensureIndex("customId");
setTimeout(function() { runStep(8); }, 100);
break;
case 8 :
benchFind(20);
setTimeout(function() { runStep(9); }, 100);
break;
case 9 :
benchRS(15);
setTimeout(function() { runStep(10); }, 100);
break;
case 10 :
benchDV(15);
trace("");
trace("done.");
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q22901
|
databaseInitialize
|
train
|
function databaseInitialize() {
// on the first load of (non-existent database), we will have no collections so we can
// detect the absence of our collections and add (and configure) them now.
var entries = db.getCollection("entries");
if (entries === null) {
entries = db.addCollection("entries");
}
// kick off any program logic or start listening to external events
runProgramLogic();
}
|
javascript
|
{
"resource": ""
}
|
q22902
|
runProgramLogic
|
train
|
function runProgramLogic() {
var entries = db.getCollection("entries");
var entryCount = entries.count();
var now = new Date();
console.log("old number of entries in database : " + entryCount);
entries.insert({ x: now.getTime(), y: 100 - entryCount });
entryCount = entries.count();
console.log("new number of entries in database : " + entryCount);
console.log("");
// manually save
db.saveDatabase(function(err) {
if (err) {
console.log(err);
}
else {
console.log("saved... it can now be loaded or reloaded with up to date data");
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22903
|
databaseInitialize
|
train
|
function databaseInitialize() {
var entries = db.getCollection("entries");
var messages = db.getCollection("messages");
// Since our LokiFsStructuredAdapter is partitioned, the default 'quickstart3.db'
// file will actually contain only the loki database shell and each of the collections
// will be saved into independent 'partition' files with numeric suffix.
// Add our main example collection if this is first run.
// This collection will save into a partition named quickstart3.db.0 (collection 0)
if (entries === null) {
// first time run so add and configure collection with some arbitrary options
entries = db.addCollection("entries", { indices: ['x'], clone: true });
}
// Now let's add a second collection only to prove that this saved partition (quickstart3.db.1)
// doesn't need to be saved every time the other partitions do if it never gets any changes
// which need to be saved. The first time we run this should be the only time we save it.
if (messages === null) {
messages = db.addCollection("messages");
messages.insert({ txt: "i will only insert into this collection during databaseInitialize" });
}
// kick off any program logic or start listening to external events
runProgramLogic();
}
|
javascript
|
{
"resource": ""
}
|
q22904
|
Balance
|
train
|
function Balance(amount, balanceDate, description, affectingActor) {
this.amount = amount;
this.balanceDate = balanceDate;
this.description = description;
this.affectingActor = affectingActor;
}
|
javascript
|
{
"resource": ""
}
|
q22905
|
fdmap
|
train
|
function fdmap(left, right) {
// PhantomJS does not support es6 Object.assign
//left = Object.assign(left, right);
Object.keys(right).forEach(function(key) {
left[key] = right[key];
});
return left;
}
|
javascript
|
{
"resource": ""
}
|
q22906
|
createDatabase
|
train
|
function createDatabase() {
var idx, a, b;
db = new loki('sorting-bench.db');
coll = db.addCollection('profile', { indices: ['a', 'b', 'c'] });
for(idx=0;idx<INITIAL_DOCUMENT_COUNT;idx++) {
coll.insert(genRandomObject());
}
}
|
javascript
|
{
"resource": ""
}
|
q22907
|
initializeDatabase
|
train
|
function initializeDatabase(silent, docCount) {
var start, end, totalTime;
var totalTimes = [];
var totalMS = 0.0;
if (typeof docCount === "undefined") {
docCount = 5000;
}
arraySize = docCount;
for (var idx = 0; idx < arraySize; idx++) {
var v1 = genRandomVal();
var v2 = genRandomVal();
start = process.hrtime();
samplecoll.insert({
customId: idx,
val: v1,
val2: v2,
val3: "more data 1234567890"
});
end = process.hrtime(start);
totalTimes.push(end);
}
if (silent === true) {
return;
}
for (var idx = 0; idx < totalTimes.length; idx++) {
totalMS += totalTimes[idx][0] * 1e3 + totalTimes[idx][1] / 1e6;
}
// let's include final find which will probably punish lazy indexes more
start = process.hrtime();
samplecoll.find({customIdx: 50});
end = process.hrtime(start);
totalTimes.push(end);
//var totalMS = end[0] * 1e3 + end[1]/1e6;
totalMS = totalMS.toFixed(2);
var rate = arraySize * 1000 / totalMS;
rate = rate.toFixed(2);
console.log("load (individual inserts) : " + totalMS + "ms (" + rate + ") ops/s (" + arraySize + " documents)");
}
|
javascript
|
{
"resource": ""
}
|
q22908
|
perfFindInterlacedInserts
|
train
|
function perfFindInterlacedInserts(multiplier) {
var start, end;
var totalTimes = [];
var totalMS = 0;
var loopIterations = arraySize;
if (typeof (multiplier) != "undefined") {
loopIterations = loopIterations * multiplier;
}
for (var idx = 0; idx < loopIterations; idx++) {
var customidx = Math.floor(Math.random() * arraySize) + 1;
start = process.hrtime();
var results = samplecoll.find({
'customId': customidx
});
// insert junk record, now (outside timing routine) to force index rebuild
var obj = samplecoll.insert({
customId: 999,
val: 999,
val2: 999,
val3: "more data 1234567890"
});
end = process.hrtime(start);
totalTimes.push(end);
}
for (var idx = 0; idx < totalTimes.length; idx++) {
totalMS += totalTimes[idx][0] * 1e3 + totalTimes[idx][1] / 1e6;
}
totalMS = totalMS.toFixed(2);
var rate = loopIterations * 1000 / totalMS;
rate = rate.toFixed(2);
console.log("interlaced inserts + coll.find() : " + totalMS + "ms (" + rate + " ops/s) " + loopIterations + " iterations");
}
|
javascript
|
{
"resource": ""
}
|
q22909
|
seedData
|
train
|
function seedData() {
var users = db.getCollection("users");
users.insert({ name: "odin", gender: "m", age: 1000, tags : ["woden", "knowlege", "sorcery", "frenzy", "runes"], items: ["gungnir"], attributes: { eyes: 1} });
users.insert({ name: "frigg", gender: "f", age: 800, tags: ["foreknowlege"], items: ["eski"] });
users.insert({ name: "thor", gender: "m", age: 35, items: ["mjolnir", "beer"] });
users.insert({ name: "sif", gender: "f", age: 30 });
users.insert({ name: "loki", gender: "m", age: 29 });
users.insert({ name: "sigyn", gender: "f", age: 29 });
users.insert({ name: "freyr", age: 400 });
users.insert({ name: "heimdallr", age: 99 });
users.insert({ name: "mimir", age: 999 });
}
|
javascript
|
{
"resource": ""
}
|
q22910
|
readTemplate
|
train
|
async function readTemplate (filename) {
const templateDir = path.join(__dirname, 'template')
return readFile(path.join(templateDir, filename), 'utf8')
}
|
javascript
|
{
"resource": ""
}
|
q22911
|
createDockerfile
|
train
|
async function createDockerfile (answers) {
const dockerfileTemplate = await readTemplate('Dockerfile')
return dockerfileTemplate
.replace(':NAME', answers.name)
.replace(':DESCRIPTION', answers.description)
.replace(':ICON', answers.icon)
.replace(':COLOR', answers.color)
}
|
javascript
|
{
"resource": ""
}
|
q22912
|
createPackageJson
|
train
|
function createPackageJson (name) {
const { version, devDependencies } = require('../package.json')
return {
name,
private: true,
main: 'index.js',
scripts: {
start: 'node ./index.js',
test: 'jest'
},
dependencies: {
'actions-toolkit': `^${version}`
},
devDependencies: {
jest: devDependencies.jest
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22913
|
train
|
function() {
if (isExpressInstallActive) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj && storedAltContent) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
}
if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
}
isExpressInstallActive = false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22914
|
Loader
|
train
|
function Loader(loadItem) {
this.AbstractLoader_constructor(loadItem, false, createjs.Types.SOUND);
// Public properties
/**
* ID used to facilitate communication with flash.
* Not doc'd because this should not be altered externally
* @property flashId
* @type {String}
*/
this.flashId = null;
}
|
javascript
|
{
"resource": ""
}
|
q22915
|
processMultiGeometry
|
train
|
function processMultiGeometry() {
const subType = type.replace(Constants.geojsonTypes.MULTI_PREFIX, '');
coordinates.forEach((subCoordinates, index) => {
const subFeature = {
type: Constants.geojsonTypes.FEATURE,
properties: geojson.properties,
geometry: {
type: subType,
coordinates: subCoordinates
}
};
supplementaryPoints = supplementaryPoints.concat(createSupplementaryPoints(subFeature, options, index));
});
}
|
javascript
|
{
"resource": ""
}
|
q22916
|
sortFeatures
|
train
|
function sortFeatures(features) {
return features.map(feature => {
if (feature.geometry.type === Constants.geojsonTypes.POLYGON) {
feature.area = area.geometry({
type: Constants.geojsonTypes.FEATURE,
property: {},
geometry: feature.geometry
});
}
return feature;
}).sort(comparator).map(feature => {
delete feature.area;
return feature;
});
}
|
javascript
|
{
"resource": ""
}
|
q22917
|
train
|
function() {
ctx.options.styles.forEach(style => {
if (ctx.map.getLayer(style.id)) {
ctx.map.removeLayer(style.id);
}
});
if (ctx.map.getSource(Constants.sources.COLD)) {
ctx.map.removeSource(Constants.sources.COLD);
}
if (ctx.map.getSource(Constants.sources.HOT)) {
ctx.map.removeSource(Constants.sources.HOT);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22918
|
mouseEventPoint
|
train
|
function mouseEventPoint(mouseEvent, container) {
const rect = container.getBoundingClientRect();
return new Point(
mouseEvent.clientX - rect.left - (container.clientLeft || 0),
mouseEvent.clientY - rect.top - (container.clientTop || 0)
);
}
|
javascript
|
{
"resource": ""
}
|
q22919
|
mapEventToBoundingBox
|
train
|
function mapEventToBoundingBox(mapEvent, buffer = 0) {
return [
[mapEvent.point.x - buffer, mapEvent.point.y - buffer],
[mapEvent.point.x + buffer, mapEvent.point.y + buffer]
];
}
|
javascript
|
{
"resource": ""
}
|
q22920
|
handleEvent
|
train
|
function handleEvent(event) {
if (event.replyToken && event.replyToken.match(/^(.)\1*$/)) {
return console.log("Test hook recieved: " + JSON.stringify(event.message));
}
switch (event.type) {
case 'message':
const message = event.message;
switch (message.type) {
case 'text':
return handleText(message, event.replyToken, event.source);
case 'image':
return handleImage(message, event.replyToken);
case 'video':
return handleVideo(message, event.replyToken);
case 'audio':
return handleAudio(message, event.replyToken);
case 'location':
return handleLocation(message, event.replyToken);
case 'sticker':
return handleSticker(message, event.replyToken);
default:
throw new Error(`Unknown message: ${JSON.stringify(message)}`);
}
case 'follow':
return replyText(event.replyToken, 'Got followed event');
case 'unfollow':
return console.log(`Unfollowed this bot: ${JSON.stringify(event)}`);
case 'join':
return replyText(event.replyToken, `Joined ${event.source.type}`);
case 'leave':
return console.log(`Left: ${JSON.stringify(event)}`);
case 'postback':
let data = event.postback.data;
if (data === 'DATE' || data === 'TIME' || data === 'DATETIME') {
data += `(${JSON.stringify(event.postback.params)})`;
}
return replyText(event.replyToken, `Got postback: ${data}`);
case 'beacon':
return replyText(event.replyToken, `Got beacon: ${event.beacon.hwid}`);
default:
throw new Error(`Unknown event: ${JSON.stringify(event)}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q22921
|
activeLinks
|
train
|
function activeLinks(sidebarContainer) {
const linksContainer = sidebarContainer.querySelector('ul');
linksContainer.addEventListener('click', e => {
if (e.target.tagName === 'A') {
Array.from(linksContainer.querySelectorAll('a')).forEach(item =>
item.classList.remove('active')
);
e.target.classList.add('active');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22922
|
Field
|
train
|
function Field({ id, children }) {
const fieldProps = useField(id);
return <FieldContext.Provider value={fieldProps}>{children}</FieldContext.Provider>;
}
|
javascript
|
{
"resource": ""
}
|
q22923
|
Ellipsis
|
train
|
function Ellipsis({ children, title, tag, ...other }) {
const CustomTagEllipsis = StyledEllipsis.withComponent(tag);
let textContent = null;
if (title !== undefined) {
textContent = title;
} else if (typeof children === 'string') {
textContent = children;
}
return (
<CustomTagEllipsis title={textContent} {...other}>
{children}
</CustomTagEllipsis>
);
}
|
javascript
|
{
"resource": ""
}
|
q22924
|
train
|
function (result) {
// update status
me.resolved = true;
me.rejected = false;
me.pending = false;
_onSuccess.forEach(function (fn) {
fn(result);
});
_process = function (onSuccess, onFail) {
onSuccess(result);
};
_resolve = _reject = function () { };
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q22925
|
train
|
function (error) {
// update status
me.resolved = false;
me.rejected = true;
me.pending = false;
_onFail.forEach(function (fn) {
fn(error);
});
_process = function (onSuccess, onFail) {
onFail(error);
};
_resolve = _reject = function () { }
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q22926
|
Pool
|
train
|
function Pool(script, options) {
if (typeof script === 'string') {
this.script = script || null;
}
else {
this.script = null;
options = script;
}
this.workers = []; // queue with all workers
this.tasks = []; // queue with tasks awaiting execution
options = options || {};
this.forkArgs = options.forkArgs || [];
this.forkOpts = options.forkOpts || {};
this.debugPortStart = (options.debugPortStart || 43210);
this.nodeWorker = options.nodeWorker;
// configuration
if (options && 'maxWorkers' in options) {
validateMaxWorkers(options.maxWorkers);
this.maxWorkers = options.maxWorkers;
}
else {
this.maxWorkers = Math.max((environment.cpus || 4) - 1, 1);
}
if (options && 'minWorkers' in options) {
if(options.minWorkers === 'max') {
this.minWorkers = Math.max((environment.cpus || 4) - 1, 1);
} else {
validateMinWorkers(options.minWorkers);
this.minWorkers = options.minWorkers;
this.maxWorkers = Math.max(this.minWorkers, this.maxWorkers); // in case minWorkers is higher than maxWorkers
}
this._ensureMinWorkers();
}
this._boundNext = this._next.bind(this);
if (this.nodeWorker === 'thread') {
WorkerHandler.ensureWorkerThreads();
}
}
|
javascript
|
{
"resource": ""
}
|
q22927
|
getDefaultWorker
|
train
|
function getDefaultWorker() {
if (environment.platform == 'browser') {
// test whether the browser supports all features that we need
if (typeof Blob === 'undefined') {
throw new Error('Blob not supported by the browser');
}
if (!window.URL || typeof window.URL.createObjectURL !== 'function') {
throw new Error('URL.createObjectURL not supported by the browser');
}
// use embedded worker.js
var blob = new Blob([require('./generated/embeddedWorker')], {type: 'text/javascript'});
return window.URL.createObjectURL(blob);
}
else {
// use external worker.js in current directory
return __dirname + '/worker.js';
}
}
|
javascript
|
{
"resource": ""
}
|
q22928
|
resolveForkOptions
|
train
|
function resolveForkOptions(opts) {
opts = opts || {};
var processExecArgv = process.execArgv.join(' ');
var inspectorActive = processExecArgv.indexOf('--inspect') !== -1;
var debugBrk = processExecArgv.indexOf('--debug-brk') !== -1;
var execArgv = [];
if (inspectorActive) {
execArgv.push('--inspect=' + opts.debugPort);
if (debugBrk) {
execArgv.push('--debug-brk');
}
}
return assign({}, opts, {
forkArgs: opts.forkArgs,
forkOpts: assign({}, opts.forkOpts, {
execArgv: (opts.forkOpts && opts.forkOpts.execArgv || [])
.concat(execArgv)
})
});
}
|
javascript
|
{
"resource": ""
}
|
q22929
|
objectToError
|
train
|
function objectToError (obj) {
var temp = new Error('')
var props = Object.keys(obj)
for (var i = 0; i < props.length; i++) {
temp[props[i]] = obj[props[i]]
}
return temp
}
|
javascript
|
{
"resource": ""
}
|
q22930
|
onError
|
train
|
function onError(error) {
me.terminated = true;
if (me.terminating && me.terminationHandler) {
me.terminationHandler(me);
}
me.terminating = false;
for (var id in me.processing) {
if (me.processing[id] !== undefined) {
me.processing[id].resolver.reject(error);
}
}
me.processing = Object.create(null);
}
|
javascript
|
{
"resource": ""
}
|
q22931
|
dispatchQueuedRequests
|
train
|
function dispatchQueuedRequests()
{
me.requestQueue.forEach(me.worker.send.bind(me.worker));
me.requestQueue = [];
}
|
javascript
|
{
"resource": ""
}
|
q22932
|
hex2packed
|
train
|
function hex2packed(str, existingPacked, existingPackedLen, bigEndianMod)
{
var packed, length = str.length, i, num, intOffset, byteOffset,
existingByteLen, shiftModifier;
if (0 !== (length % 2))
{
throw new Error("String of HEX type must be in byte increments");
}
packed = existingPacked || [0];
existingPackedLen = existingPackedLen || 0;
existingByteLen = existingPackedLen >>> 3;
shiftModifier = (bigEndianMod === -1) ? 3 : 0;
for (i = 0; i < length; i += 2)
{
num = parseInt(str.substr(i, 2), 16);
if (!isNaN(num))
{
byteOffset = (i >>> 1) + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset)
{
packed.push(0);
}
packed[intOffset] |= num << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
}
else
{
throw new Error("String of HEX type contains invalid characters");
}
}
return {"value" : packed, "binLen" : length * 4 + existingPackedLen};
}
|
javascript
|
{
"resource": ""
}
|
q22933
|
bytes2packed
|
train
|
function bytes2packed(str, existingPacked, existingPackedLen, bigEndianMod)
{
var packed, codePnt, i, existingByteLen, intOffset,
byteOffset, shiftModifier;
packed = existingPacked || [0];
existingPackedLen = existingPackedLen || 0;
existingByteLen = existingPackedLen >>> 3;
shiftModifier = (bigEndianMod === -1) ? 3 : 0;
for (i = 0; i < str.length; i += 1)
{
codePnt = str.charCodeAt(i);
byteOffset = i + existingByteLen;
intOffset = byteOffset >>> 2;
if (packed.length <= intOffset)
{
packed.push(0);
}
packed[intOffset] |= codePnt << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
}
return {"value" : packed, "binLen" : str.length * 8 + existingPackedLen};
}
|
javascript
|
{
"resource": ""
}
|
q22934
|
b642packed
|
train
|
function b642packed(str, existingPacked, existingPackedLen, bigEndianMod)
{
var packed, byteCnt = 0, index, i, j, tmpInt, strPart, firstEqual,
b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
existingByteLen, intOffset, byteOffset, shiftModifier;
if (-1 === str.search(/^[a-zA-Z0-9=+\/]+$/))
{
throw new Error("Invalid character in base-64 string");
}
firstEqual = str.indexOf("=");
str = str.replace(/\=/g, "");
if ((-1 !== firstEqual) && (firstEqual < str.length))
{
throw new Error("Invalid '=' found in base-64 string");
}
packed = existingPacked || [0];
existingPackedLen = existingPackedLen || 0;
existingByteLen = existingPackedLen >>> 3;
shiftModifier = (bigEndianMod === -1) ? 3 : 0;
for (i = 0; i < str.length; i += 4)
{
strPart = str.substr(i, 4);
tmpInt = 0;
for (j = 0; j < strPart.length; j += 1)
{
index = b64Tab.indexOf(strPart[j]);
tmpInt |= index << (18 - (6 * j));
}
for (j = 0; j < strPart.length - 1; j += 1)
{
byteOffset = byteCnt + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset)
{
packed.push(0);
}
packed[intOffset] |= ((tmpInt >>> (16 - (j * 8))) & 0xFF) <<
(8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
byteCnt += 1;
}
}
return {"value" : packed, "binLen" : byteCnt * 8 + existingPackedLen};
}
|
javascript
|
{
"resource": ""
}
|
q22935
|
arraybuffer2packed
|
train
|
function arraybuffer2packed(arr, existingPacked, existingPackedLen, bigEndianMod)
{
var packed, i, existingByteLen, intOffset, byteOffset, shiftModifier, arrView;
packed = existingPacked || [0];
existingPackedLen = existingPackedLen || 0;
existingByteLen = existingPackedLen >>> 3;
shiftModifier = (bigEndianMod === -1) ? 3 : 0;
arrView = new Uint8Array(arr);
for (i = 0; i < arr.byteLength; i += 1)
{
byteOffset = i + existingByteLen;
intOffset = byteOffset >>> 2;
if (packed.length <= intOffset)
{
packed.push(0);
}
packed[intOffset] |= arrView[i] << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
}
return {"value" : packed, "binLen" : arr.byteLength * 8 + existingPackedLen};
}
|
javascript
|
{
"resource": ""
}
|
q22936
|
packed2b64
|
train
|
function packed2b64(packed, outputLength, bigEndianMod, formatOpts)
{
var str = "", length = outputLength / 8, i, j, triplet, int1, int2, shiftModifier,
b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
shiftModifier = (bigEndianMod === -1) ? 3 : 0;
for (i = 0; i < length; i += 3)
{
int1 = ((i + 1) < length) ? packed[(i + 1) >>> 2] : 0;
int2 = ((i + 2) < length) ? packed[(i + 2) >>> 2] : 0;
triplet = (((packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xFF) << 16) |
(((int1 >>> (8 * (shiftModifier + bigEndianMod * ((i + 1) % 4)))) & 0xFF) << 8) |
((int2 >>> (8 * (shiftModifier + bigEndianMod * ((i + 2) % 4)))) & 0xFF);
for (j = 0; j < 4; j += 1)
{
if (i * 8 + j * 6 <= outputLength)
{
str += b64Tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
}
else
{
str += formatOpts["b64Pad"];
}
}
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q22937
|
packed2bytes
|
train
|
function packed2bytes(packed, outputLength, bigEndianMod)
{
var str = "", length = outputLength / 8, i, srcByte, shiftModifier;
shiftModifier = (bigEndianMod === -1) ? 3 : 0;
for (i = 0; i < length; i += 1)
{
srcByte = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xFF;
str += String.fromCharCode(srcByte);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q22938
|
packed2arraybuffer
|
train
|
function packed2arraybuffer(packed, outputLength, bigEndianMod)
{
var length = outputLength / 8, i, retVal = new ArrayBuffer(length), shiftModifier, arrView;
arrView = new Uint8Array(retVal);
shiftModifier = (bigEndianMod === -1) ? 3 : 0;
for (i = 0; i < length; i += 1)
{
arrView[i] = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xFF;
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q22939
|
getOutputOpts
|
train
|
function getOutputOpts(options)
{
var retVal = {"outputUpper" : false, "b64Pad" : "=", "shakeLen" : -1},
outputOptions;
outputOptions = options || {};
retVal["outputUpper"] = outputOptions["outputUpper"] || false;
if (true === outputOptions.hasOwnProperty("b64Pad"))
{
retVal["b64Pad"] = outputOptions["b64Pad"];
}
if ((true === outputOptions.hasOwnProperty("shakeLen")) && ((8 & SUPPORTED_ALGS) !== 0))
{
if (outputOptions["shakeLen"] % 8 !== 0)
{
throw new Error("shakeLen must be a multiple of 8");
}
retVal["shakeLen"] = outputOptions["shakeLen"];
}
if ("boolean" !== typeof(retVal["outputUpper"]))
{
throw new Error("Invalid outputUpper formatting option");
}
if ("string" !== typeof(retVal["b64Pad"]))
{
throw new Error("Invalid b64Pad formatting option");
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q22940
|
rotl_64
|
train
|
function rotl_64(x, n)
{
if (n > 32)
{
n = n - 32;
return new Int_64(
x.lowOrder << n | x.highOrder >>> (32 - n),
x.highOrder << n | x.lowOrder >>> (32 - n)
);
}
else if (0 !== n)
{
return new Int_64(
x.highOrder << n | x.lowOrder >>> (32 - n),
x.lowOrder << n | x.highOrder >>> (32 - n)
);
}
else
{
return x;
}
}
|
javascript
|
{
"resource": ""
}
|
q22941
|
rotr_64
|
train
|
function rotr_64(x, n)
{
var retVal = null, tmp = new Int_64(x.highOrder, x.lowOrder);
if (32 >= n)
{
retVal = new Int_64(
(tmp.highOrder >>> n) | ((tmp.lowOrder << (32 - n)) & 0xFFFFFFFF),
(tmp.lowOrder >>> n) | ((tmp.highOrder << (32 - n)) & 0xFFFFFFFF)
);
}
else
{
retVal = new Int_64(
(tmp.lowOrder >>> (n - 32)) | ((tmp.highOrder << (64 - n)) & 0xFFFFFFFF),
(tmp.highOrder >>> (n - 32)) | ((tmp.lowOrder << (64 - n)) & 0xFFFFFFFF)
);
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q22942
|
shr_64
|
train
|
function shr_64(x, n)
{
var retVal = null;
if (32 >= n)
{
retVal = new Int_64(
x.highOrder >>> n,
x.lowOrder >>> n | ((x.highOrder << (32 - n)) & 0xFFFFFFFF)
);
}
else
{
retVal = new Int_64(
0,
x.highOrder >>> (n - 32)
);
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q22943
|
ch_64
|
train
|
function ch_64(x, y, z)
{
return new Int_64(
(x.highOrder & y.highOrder) ^ (~x.highOrder & z.highOrder),
(x.lowOrder & y.lowOrder) ^ (~x.lowOrder & z.lowOrder)
);
}
|
javascript
|
{
"resource": ""
}
|
q22944
|
maj_32
|
train
|
function maj_32(x, y, z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
|
javascript
|
{
"resource": ""
}
|
q22945
|
maj_64
|
train
|
function maj_64(x, y, z)
{
return new Int_64(
(x.highOrder & y.highOrder) ^
(x.highOrder & z.highOrder) ^
(y.highOrder & z.highOrder),
(x.lowOrder & y.lowOrder) ^
(x.lowOrder & z.lowOrder) ^
(y.lowOrder & z.lowOrder)
);
}
|
javascript
|
{
"resource": ""
}
|
q22946
|
sigma0_64
|
train
|
function sigma0_64(x)
{
var rotr28 = rotr_64(x, 28), rotr34 = rotr_64(x, 34),
rotr39 = rotr_64(x, 39);
return new Int_64(
rotr28.highOrder ^ rotr34.highOrder ^ rotr39.highOrder,
rotr28.lowOrder ^ rotr34.lowOrder ^ rotr39.lowOrder);
}
|
javascript
|
{
"resource": ""
}
|
q22947
|
sigma1_64
|
train
|
function sigma1_64(x)
{
var rotr14 = rotr_64(x, 14), rotr18 = rotr_64(x, 18),
rotr41 = rotr_64(x, 41);
return new Int_64(
rotr14.highOrder ^ rotr18.highOrder ^ rotr41.highOrder,
rotr14.lowOrder ^ rotr18.lowOrder ^ rotr41.lowOrder);
}
|
javascript
|
{
"resource": ""
}
|
q22948
|
gamma0_64
|
train
|
function gamma0_64(x)
{
var rotr1 = rotr_64(x, 1), rotr8 = rotr_64(x, 8), shr7 = shr_64(x, 7);
return new Int_64(
rotr1.highOrder ^ rotr8.highOrder ^ shr7.highOrder,
rotr1.lowOrder ^ rotr8.lowOrder ^ shr7.lowOrder
);
}
|
javascript
|
{
"resource": ""
}
|
q22949
|
gamma1_64
|
train
|
function gamma1_64(x)
{
var rotr19 = rotr_64(x, 19), rotr61 = rotr_64(x, 61),
shr6 = shr_64(x, 6);
return new Int_64(
rotr19.highOrder ^ rotr61.highOrder ^ shr6.highOrder,
rotr19.lowOrder ^ rotr61.lowOrder ^ shr6.lowOrder
);
}
|
javascript
|
{
"resource": ""
}
|
q22950
|
safeAdd_32_2
|
train
|
function safeAdd_32_2(a, b)
{
var lsw = (a & 0xFFFF) + (b & 0xFFFF),
msw = (a >>> 16) + (b >>> 16) + (lsw >>> 16);
return ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
}
|
javascript
|
{
"resource": ""
}
|
q22951
|
safeAdd_32_4
|
train
|
function safeAdd_32_4(a, b, c, d)
{
var lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF),
msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) +
(lsw >>> 16);
return ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
}
|
javascript
|
{
"resource": ""
}
|
q22952
|
safeAdd_32_5
|
train
|
function safeAdd_32_5(a, b, c, d, e)
{
var lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF) +
(e & 0xFFFF),
msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) +
(e >>> 16) + (lsw >>> 16);
return ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
}
|
javascript
|
{
"resource": ""
}
|
q22953
|
safeAdd_64_2
|
train
|
function safeAdd_64_2(x, y)
{
var lsw, msw, lowOrder, highOrder;
lsw = (x.lowOrder & 0xFFFF) + (y.lowOrder & 0xFFFF);
msw = (x.lowOrder >>> 16) + (y.lowOrder >>> 16) + (lsw >>> 16);
lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
lsw = (x.highOrder & 0xFFFF) + (y.highOrder & 0xFFFF) + (msw >>> 16);
msw = (x.highOrder >>> 16) + (y.highOrder >>> 16) + (lsw >>> 16);
highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
return new Int_64(highOrder, lowOrder);
}
|
javascript
|
{
"resource": ""
}
|
q22954
|
safeAdd_64_4
|
train
|
function safeAdd_64_4(a, b, c, d)
{
var lsw, msw, lowOrder, highOrder;
lsw = (a.lowOrder & 0xFFFF) + (b.lowOrder & 0xFFFF) +
(c.lowOrder & 0xFFFF) + (d.lowOrder & 0xFFFF);
msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) +
(c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (lsw >>> 16);
lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
lsw = (a.highOrder & 0xFFFF) + (b.highOrder & 0xFFFF) +
(c.highOrder & 0xFFFF) + (d.highOrder & 0xFFFF) + (msw >>> 16);
msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) +
(c.highOrder >>> 16) + (d.highOrder >>> 16) + (lsw >>> 16);
highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
return new Int_64(highOrder, lowOrder);
}
|
javascript
|
{
"resource": ""
}
|
q22955
|
safeAdd_64_5
|
train
|
function safeAdd_64_5(a, b, c, d, e)
{
var lsw, msw, lowOrder, highOrder;
lsw = (a.lowOrder & 0xFFFF) + (b.lowOrder & 0xFFFF) +
(c.lowOrder & 0xFFFF) + (d.lowOrder & 0xFFFF) +
(e.lowOrder & 0xFFFF);
msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) +
(c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (e.lowOrder >>> 16) +
(lsw >>> 16);
lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
lsw = (a.highOrder & 0xFFFF) + (b.highOrder & 0xFFFF) +
(c.highOrder & 0xFFFF) + (d.highOrder & 0xFFFF) +
(e.highOrder & 0xFFFF) + (msw >>> 16);
msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) +
(c.highOrder >>> 16) + (d.highOrder >>> 16) +
(e.highOrder >>> 16) + (lsw >>> 16);
highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF);
return new Int_64(highOrder, lowOrder);
}
|
javascript
|
{
"resource": ""
}
|
q22956
|
xor_64_2
|
train
|
function xor_64_2(a, b)
{
return new Int_64(
a.highOrder ^ b.highOrder,
a.lowOrder ^ b.lowOrder
);
}
|
javascript
|
{
"resource": ""
}
|
q22957
|
xor_64_5
|
train
|
function xor_64_5(a, b, c, d, e)
{
return new Int_64(
a.highOrder ^ b.highOrder ^ c.highOrder ^ d.highOrder ^ e.highOrder,
a.lowOrder ^ b.lowOrder ^ c.lowOrder ^ d.lowOrder ^ e.lowOrder
);
}
|
javascript
|
{
"resource": ""
}
|
q22958
|
cloneSHA3State
|
train
|
function cloneSHA3State(state) {
var clone = [], i;
for (i = 0; i < 5; i += 1)
{
clone[i] = state[i].slice();
}
return clone;
}
|
javascript
|
{
"resource": ""
}
|
q22959
|
getNewState
|
train
|
function getNewState(variant)
{
var retVal = [], H_trunc, H_full, i;
if (("SHA-1" === variant) && ((1 & SUPPORTED_ALGS) !== 0))
{
retVal = [
0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0
];
}
else if ((variant.lastIndexOf("SHA-", 0) === 0) && ((6 & SUPPORTED_ALGS) !== 0))
{
H_trunc = [
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
];
H_full = [
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
];
switch (variant)
{
case "SHA-224":
retVal = H_trunc;
break;
case "SHA-256":
retVal = H_full;
break;
case "SHA-384":
retVal = [
new Int_64(0xcbbb9d5d, H_trunc[0]),
new Int_64(0x0629a292a, H_trunc[1]),
new Int_64(0x9159015a, H_trunc[2]),
new Int_64(0x0152fecd8, H_trunc[3]),
new Int_64(0x67332667, H_trunc[4]),
new Int_64(0x98eb44a87, H_trunc[5]),
new Int_64(0xdb0c2e0d, H_trunc[6]),
new Int_64(0x047b5481d, H_trunc[7])
];
break;
case "SHA-512":
retVal = [
new Int_64(H_full[0], 0xf3bcc908),
new Int_64(H_full[1], 0x84caa73b),
new Int_64(H_full[2], 0xfe94f82b),
new Int_64(H_full[3], 0x5f1d36f1),
new Int_64(H_full[4], 0xade682d1),
new Int_64(H_full[5], 0x2b3e6c1f),
new Int_64(H_full[6], 0xfb41bd6b),
new Int_64(H_full[7], 0x137e2179)
];
break;
default:
throw new Error("Unknown SHA variant");
}
}
else if (((variant.lastIndexOf("SHA3-", 0) === 0) || (variant.lastIndexOf("SHAKE", 0) === 0)) &&
((8 & SUPPORTED_ALGS) !== 0))
{
for (i = 0; i < 5; i += 1)
{
retVal[i] = [new Int_64(0, 0), new Int_64(0, 0), new Int_64(0, 0), new Int_64(0, 0), new Int_64(0, 0)];
}
}
else
{
throw new Error("No SHA variants supported");
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q22960
|
roundSHA1
|
train
|
function roundSHA1(block, H)
{
var W = [], a, b, c, d, e, T, ch = ch_32, parity = parity_32,
maj = maj_32, rotl = rotl_32, safeAdd_2 = safeAdd_32_2, t,
safeAdd_5 = safeAdd_32_5;
a = H[0];
b = H[1];
c = H[2];
d = H[3];
e = H[4];
for (t = 0; t < 80; t += 1)
{
if (t < 16)
{
W[t] = block[t];
}
else
{
W[t] = rotl(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
}
if (t < 20)
{
T = safeAdd_5(rotl(a, 5), ch(b, c, d), e, 0x5a827999, W[t]);
}
else if (t < 40)
{
T = safeAdd_5(rotl(a, 5), parity(b, c, d), e, 0x6ed9eba1, W[t]);
}
else if (t < 60)
{
T = safeAdd_5(rotl(a, 5), maj(b, c, d), e, 0x8f1bbcdc, W[t]);
} else {
T = safeAdd_5(rotl(a, 5), parity(b, c, d), e, 0xca62c1d6, W[t]);
}
e = d;
d = c;
c = rotl(b, 30);
b = a;
a = T;
}
H[0] = safeAdd_2(a, H[0]);
H[1] = safeAdd_2(b, H[1]);
H[2] = safeAdd_2(c, H[2]);
H[3] = safeAdd_2(d, H[3]);
H[4] = safeAdd_2(e, H[4]);
return H;
}
|
javascript
|
{
"resource": ""
}
|
q22961
|
finalizeSHA1
|
train
|
function finalizeSHA1(remainder, remainderBinLen, processedBinLen, H, outputLen)
{
var i, appendedMessageLength, offset, totalLen;
/* The 65 addition is a hack but it works. The correct number is
actually 72 (64 + 8) but the below math fails if
remainderBinLen + 72 % 512 = 0. Since remainderBinLen % 8 = 0,
"shorting" the addition is OK. */
offset = (((remainderBinLen + 65) >>> 9) << 4) + 15;
while (remainder.length <= offset)
{
remainder.push(0);
}
/* Append '1' at the end of the binary string */
remainder[remainderBinLen >>> 5] |= 0x80 << (24 - (remainderBinLen % 32));
/* Append length of binary string in the position such that the new
* length is a multiple of 512. Logic does not work for even multiples
* of 512 but there can never be even multiples of 512. JavaScript
* numbers are limited to 2^53 so it's "safe" to treat the totalLen as
* a 64-bit integer. */
totalLen = remainderBinLen + processedBinLen;
remainder[offset] = totalLen & 0xFFFFFFFF;
/* Bitwise operators treat the operand as a 32-bit number so need to
* use hacky division and round to get access to upper 32-ish bits */
remainder[offset - 1] = (totalLen / TWO_PWR_32) | 0;
appendedMessageLength = remainder.length;
/* This will always be at least 1 full chunk */
for (i = 0; i < appendedMessageLength; i += 16)
{
H = roundSHA1(remainder.slice(i, i + 16), H);
}
return H;
}
|
javascript
|
{
"resource": ""
}
|
q22962
|
finalizeSHA3
|
train
|
function finalizeSHA3(remainder, remainderBinLen, processedBinLen, state, blockSize, delimiter, outputLen)
{
var i, retVal = [], binaryStringInc = blockSize >>> 5, state_offset = 0,
remainderIntLen = remainderBinLen >>> 5, temp;
/* Process as many blocks as possible, some may be here for multiple rounds
with SHAKE
*/
for (i = 0; i < remainderIntLen && remainderBinLen >= blockSize; i += binaryStringInc)
{
state = roundSHA3(remainder.slice(i, i + binaryStringInc), state);
remainderBinLen -= blockSize;
}
remainder = remainder.slice(i);
remainderBinLen = remainderBinLen % blockSize;
/* Pad out the remainder to a full block */
while (remainder.length < binaryStringInc)
{
remainder.push(0);
}
/* Find the next "empty" byte for the 0x80 and append it via an xor */
i = remainderBinLen >>> 3;
remainder[i >> 2] ^= delimiter << (8 * (i % 4));
remainder[binaryStringInc - 1] ^= 0x80000000;
state = roundSHA3(remainder, state);
while (retVal.length * 32 < outputLen)
{
temp = state[state_offset % 5][(state_offset / 5) | 0];
retVal.push(temp.lowOrder);
if (retVal.length * 32 >= outputLen)
{
break;
}
retVal.push(temp.highOrder);
state_offset += 1;
if (0 === ((state_offset * 64) % blockSize))
{
roundSHA3(null, state);
}
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q22963
|
batchMethod
|
train
|
function batchMethod (obj, method) {
const descriptor = Object.getOwnPropertyDescriptor(obj, method)
if (descriptor) {
const newDescriptor = Object.assign({}, descriptor, {
set (value) {
return descriptor.set.call(this, batchFn(value))
}
})
Object.defineProperty(obj, method, newDescriptor)
}
}
|
javascript
|
{
"resource": ""
}
|
q22964
|
toSet
|
train
|
function toSet(arr) {
const set = {};
arr.forEach((e) => (set[e] = true));
return set;
}
|
javascript
|
{
"resource": ""
}
|
q22965
|
copy
|
train
|
function copy() {
const nodes = [];
const cnodes = [];
const mapping = {};
this.each((node) => {
nodes.push(node);
const cnode = new Node(node.id, node.data);
cnodes.push(cnode);
mapping[cnode.id] = cnode;
});
cnodes.forEach((cnode, i) => {
const node = nodes[i];
cnode.children = node.children.map((c) => mapping[c.id]);
});
if (this.id === undefined) {
const root = new Node(undefined, undefined);
root.children = this.children.map((c) => mapping[c.id]);
} else {
return mapping[this.id];
}
}
|
javascript
|
{
"resource": ""
}
|
q22966
|
getLumenPrice
|
train
|
function getLumenPrice() {
return Promise.all([
rp('https://poloniex.com/public?command=returnTicker')
.then(data => {
return parseFloat(JSON.parse(data).BTC_STR.last);
})
.catch(() => {
return null;
})
,
rp('https://bittrex.com/api/v1.1/public/getticker?market=BTC-XLM')
.then(data => {
return parseFloat(JSON.parse(data).result.Last);
})
.catch(() => {
return null;
})
,
rp('https://api.kraken.com/0/public/Ticker?pair=XLMXBT')
.then(data => {
return parseFloat(JSON.parse(data).result.XXLMXXBT.c[0]);
})
.catch(() => {
return null;
})
])
.then(allPrices => {
return _.round(_.mean(_.filter(allPrices, price => price !== null)), 8);
})
}
|
javascript
|
{
"resource": ""
}
|
q22967
|
showPrompt
|
train
|
function showPrompt () {
return new Promise(function (resolve, reject) {
var msg = 'May Cordova anonymously report usage statistics to improve the tool over time?';
insight._permissionTimeout = module.exports.timeoutInSecs || 30;
insight.askPermission(msg, function (unused, optIn) {
var EOL = require('os').EOL;
if (optIn) {
console.log(EOL + 'Thanks for opting into telemetry to help us improve cordova.');
module.exports.track('telemetry', 'on', 'via-cli-prompt-choice', 'successful');
} else {
console.log(EOL + 'You have been opted out of telemetry. To change this, run: cordova telemetry on.');
// Always track telemetry opt-outs! (whether opted-in or opted-out)
module.exports.track('telemetry', 'off', 'via-cli-prompt-choice', 'successful');
}
resolve(optIn);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q22968
|
onSameRow
|
train
|
function onSameRow(a, b, minimumStartDifference) {
return (
// Occupies the same start slot.
Math.abs(b.start - a.start) < minimumStartDifference ||
// A's start slot overlaps with b's end slot.
(b.start > a.start && b.start < a.end)
)
}
|
javascript
|
{
"resource": ""
}
|
q22969
|
withTheme
|
train
|
function withTheme(WrappedComponent) {
const displayName =
WrappedComponent.displayName || WrappedComponent.name || 'Component'
return class extends React.Component {
static displayName = `withTheme(${displayName})`
render() {
return (
<ThemeConsumer>
{theme => <WrappedComponent theme={theme} {...this.props} />}
</ThemeConsumer>
)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22970
|
stripQuotes
|
train
|
function stripQuotes (str) {
var a = str.charCodeAt(0);
var b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27)
? str.slice(1, -1)
: str
}
|
javascript
|
{
"resource": ""
}
|
q22971
|
getPathCharType
|
train
|
function getPathCharType (ch) {
if (ch === undefined || ch === null) { return 'eof' }
const code = ch.charCodeAt(0);
switch (code) {
case 0x5B: // [
case 0x5D: // ]
case 0x2E: // .
case 0x22: // "
case 0x27: // '
return ch
case 0x5F: // _
case 0x24: // $
case 0x2D: // -
return 'ident'
case 0x09: // Tab
case 0x0A: // Newline
case 0x0D: // Return
case 0xA0: // No-break space
case 0xFEFF: // Byte Order Mark
case 0x2028: // Line Separator
case 0x2029: // Paragraph Separator
return 'ws'
}
return 'ident'
}
|
javascript
|
{
"resource": ""
}
|
q22972
|
parse$1
|
train
|
function parse$1 (path) {
const keys = [];
let index = -1;
let mode = BEFORE_PATH;
let subPathDepth = 0;
let c;
let key;
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[PUSH] = function () {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[APPEND] = function () {
if (key === undefined) {
key = newChar;
} else {
key += newChar;
}
};
actions[INC_SUB_PATH_DEPTH] = function () {
actions[APPEND]();
subPathDepth++;
};
actions[PUSH_SUB_PATH] = function () {
if (subPathDepth > 0) {
subPathDepth--;
mode = IN_SUB_PATH;
actions[APPEND]();
} else {
subPathDepth = 0;
key = formatSubPath(key);
if (key === false) {
return false
} else {
actions[PUSH]();
}
}
};
function maybeUnescapeQuote () {
const nextChar = path[index + 1];
if ((mode === IN_SINGLE_QUOTE && nextChar === "'") ||
(mode === IN_DOUBLE_QUOTE && nextChar === '"')) {
index++;
newChar = '\\' + nextChar;
actions[APPEND]();
return true
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap['else'] || ERROR;
if (transition === ERROR) {
return // parse error
}
mode = transition[0];
action = actions[transition[1]];
if (action) {
newChar = transition[2];
newChar = newChar === undefined
? c
: newChar;
if (action() === false) {
return
}
}
if (mode === AFTER_PATH) {
return keys
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22973
|
wrapTree
|
train
|
function wrapTree(t) {
var wt = {
t: t,
prelim: 0,
mod: 0,
shift: 0,
change: 0,
msel: 0,
mser: 0,
};
t.x = 0;
t.y = 0;
if (size) {
wt.x_size = 1;
wt.y_size = 1;
}
else if (typeof nodeSize == "object") { // fixed array
wt.x_size = nodeSize[0];
wt.y_size = nodeSize[1];
}
else { // use nodeSize function
var ns = nodeSize(t);
wt.x_size = ns[0];
wt.y_size = ns[1];
}
if (setNodeSizes) {
t.x_size = wt.x_size;
t.y_size = wt.y_size;
}
var children = [];
var num_children = t.children ? t.children.length : 0;
for (var i = 0; i < num_children; ++i) {
children.push(wrapTree(t.children[i]));
}
wt.children = children;
wt.num_children = num_children;
return wt;
}
|
javascript
|
{
"resource": ""
}
|
q22974
|
zerothWalk
|
train
|
function zerothWalk(wt, initial) {
wt.t.y = initial;
wt.t.depth = 0;
_zerothWalk(wt);
}
|
javascript
|
{
"resource": ""
}
|
q22975
|
setRightThread
|
train
|
function setRightThread(wt, i, sr, modsumsr) {
var ri = wt.children[i].er;
ri.tr = sr;
var diff = (modsumsr - sr.mod) - wt.children[i].mser;
ri.mod += diff;
ri.prelim -= diff;
wt.children[i].er = wt.children[i - 1].er;
wt.children[i].mser = wt.children[i - 1].mser;
}
|
javascript
|
{
"resource": ""
}
|
q22976
|
positionRoot
|
train
|
function positionRoot(wt) {
wt.prelim = ( wt.children[0].prelim +
wt.children[0].mod -
wt.children[0].x_size/2 +
wt.children[wt.num_children - 1].mod +
wt.children[wt.num_children - 1].prelim +
wt.children[wt.num_children - 1].x_size/2) / 2;
}
|
javascript
|
{
"resource": ""
}
|
q22977
|
addChildSpacing
|
train
|
function addChildSpacing(wt) {
var d = 0, modsumdelta = 0;
for (var i = 0; i < wt.num_children; i++) {
d += wt.children[i].shift;
modsumdelta += d + wt.children[i].change;
wt.children[i].mod += modsumdelta;
}
}
|
javascript
|
{
"resource": ""
}
|
q22978
|
renormalize
|
train
|
function renormalize(wt) {
// If a fixed tree size is specified, scale x and y based on the extent.
// Compute the left-most, right-most, and depth-most nodes for extents.
if (size != null) {
var left = wt,
right = wt,
bottom = wt;
var toVisit = [wt],
node;
while (node = toVisit.pop()) {
var t = node.t;
if (t.x < left.t.x) left = node;
if (t.x > right.t.x) right = node;
if (t.depth > bottom.t.depth) bottom = node;
if (node.children)
toVisit = toVisit.concat(node.children);
}
var sep = separation == null ? 0.5 : separation(left.t, right.t)/2;
var tx = sep - left.t.x;
var kx = size[0] / (right.t.x + sep + tx);
var ky = size[1] / (bottom.t.depth > 0 ? bottom.t.depth : 1);
toVisit = [wt];
while (node = toVisit.pop()) {
var t = node.t;
t.x = (t.x + tx) * kx;
t.y = t.depth * ky;
if (setNodeSizes) {
t.x_size *= kx;
t.y_size *= ky;
}
if (node.children)
toVisit = toVisit.concat(node.children);
}
}
// Else either a fixed node size, or node size function was specified.
// In this case, we translate such that the root node is at x = 0.
else {
var rootX = wt.t.x;
moveRight(wt, -rootX);
}
}
|
javascript
|
{
"resource": ""
}
|
q22979
|
getSyncPage
|
train
|
function getSyncPage (http, items, query, { paginate }) {
if (query.nextSyncToken) {
query.sync_token = query.nextSyncToken
delete query.nextSyncToken
}
if (query.nextPageToken) {
query.sync_token = query.nextPageToken
delete query.nextPageToken
}
if (query.sync_token) {
delete query.initial
delete query.type
delete query.content_type
}
return http.get('sync', createRequestConfig({query: query}))
.then((response) => {
const data = response.data
items = items.concat(data.items)
if (data.nextPageUrl) {
if (paginate) {
delete query.initial
query.sync_token = getToken(data.nextPageUrl)
return getSyncPage(http, items, query, { paginate })
}
return {
items: items,
nextPageToken: getToken(data.nextPageUrl)
}
} else if (data.nextSyncUrl) {
return {
items: items,
nextSyncToken: getToken(data.nextSyncUrl)
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q22980
|
scrollIntoView
|
train
|
function scrollIntoView(node, menuNode) {
if (node === null) {
return
}
const actions = computeScrollIntoView(node, {
boundary: menuNode,
block: 'nearest',
scrollMode: 'if-needed',
})
actions.forEach(({el, top, left}) => {
el.scrollTop = top
el.scrollLeft = left
})
}
|
javascript
|
{
"resource": ""
}
|
q22981
|
debounce
|
train
|
function debounce(fn, time) {
let timeoutId
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId)
}
}
function wrapper(...args) {
cancel()
timeoutId = setTimeout(() => {
timeoutId = null
fn(...args)
}, time)
}
wrapper.cancel = cancel
return wrapper
}
|
javascript
|
{
"resource": ""
}
|
q22982
|
callAllEventHandlers
|
train
|
function callAllEventHandlers(...fns) {
return (event, ...args) =>
fns.some(fn => {
if (fn) {
fn(event, ...args)
}
return (
event.preventDownshiftDefault ||
(event.hasOwnProperty('nativeEvent') &&
event.nativeEvent.preventDownshiftDefault)
)
})
}
|
javascript
|
{
"resource": ""
}
|
q22983
|
getNextWrappingIndex
|
train
|
function getNextWrappingIndex(moveAmount, baseIndex, itemCount) {
const itemsLastIndex = itemCount - 1
if (
typeof baseIndex !== 'number' ||
baseIndex < 0 ||
baseIndex >= itemCount
) {
baseIndex = moveAmount > 0 ? -1 : itemsLastIndex + 1
}
let newIndex = baseIndex + moveAmount
if (newIndex < 0) {
newIndex = itemsLastIndex
} else if (newIndex > itemsLastIndex) {
newIndex = 0
}
return newIndex
}
|
javascript
|
{
"resource": ""
}
|
q22984
|
getStatusDiv
|
train
|
function getStatusDiv() {
if (statusDiv) {
return statusDiv
}
statusDiv = document.createElement('div')
statusDiv.setAttribute('id', 'a11y-status-message')
statusDiv.setAttribute('role', 'status')
statusDiv.setAttribute('aria-live', 'polite')
statusDiv.setAttribute('aria-relevant', 'additions text')
Object.assign(statusDiv.style, {
border: '0',
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: '0',
position: 'absolute',
width: '1px',
})
document.body.appendChild(statusDiv)
return statusDiv
}
|
javascript
|
{
"resource": ""
}
|
q22985
|
train
|
function(controller) {
// TODO listening?
this.__ul.removeChild(controller.__li);
this.__controllers.splice(this.__controllers.indexOf(controller), 1);
const _this = this;
common.defer(function() {
_this.onResize();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q22986
|
getEyeMatrices
|
train
|
function getEyeMatrices( frameData ) {
// Compute the matrix for the position of the head based on the pose
if ( frameData.pose.orientation ) {
poseOrientation.fromArray( frameData.pose.orientation );
headMatrix.makeRotationFromQuaternion( poseOrientation );
} else {
headMatrix.identity();
}
if ( frameData.pose.position ) {
posePosition.fromArray( frameData.pose.position );
headMatrix.setPosition( posePosition );
}
// The view matrix transforms vertices from sitting space to eye space. As such, the view matrix can be thought of as a product of two matrices:
// headToEyeMatrix * sittingToHeadMatrix
// The headMatrix that we've calculated above is the model matrix of the head in sitting space, which is the inverse of sittingToHeadMatrix.
// So when we multiply the view matrix with headMatrix, we're left with headToEyeMatrix:
// viewMatrix * headMatrix = headToEyeMatrix * sittingToHeadMatrix * headMatrix = headToEyeMatrix
eyeMatrixL.fromArray( frameData.leftViewMatrix );
eyeMatrixL.multiply( headMatrix );
eyeMatrixR.fromArray( frameData.rightViewMatrix );
eyeMatrixR.multiply( headMatrix );
// The eye's model matrix in head space is the inverse of headToEyeMatrix we calculated above.
eyeMatrixL.getInverse( eyeMatrixL );
eyeMatrixR.getInverse( eyeMatrixR );
}
|
javascript
|
{
"resource": ""
}
|
q22987
|
rng_seed_int
|
train
|
function rng_seed_int(x) {
rng_pool[rng_pptr++] ^= x & 255;
rng_pool[rng_pptr++] ^= (x >> 8) & 255;
rng_pool[rng_pptr++] ^= (x >> 16) & 255;
rng_pool[rng_pptr++] ^= (x >> 24) & 255;
if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
}
|
javascript
|
{
"resource": ""
}
|
q22988
|
curveFpDecodePointHex
|
train
|
function curveFpDecodePointHex(s) {
switch(parseInt(s.substr(0,2), 16)) { // first byte
case 0:
return this.infinity;
case 2:
case 3:
// point compression not supported yet
return null;
case 4:
case 6:
case 7:
var len = (s.length - 2) / 2;
var xHex = s.substr(2, len);
var yHex = s.substr(len+2, len);
return new ECPointFp(this,
this.fromBigInteger(new BigInteger(xHex, 16)),
this.fromBigInteger(new BigInteger(yHex, 16)));
default: // unsupported
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q22989
|
build_lib_sourcemap
|
train
|
function build_lib_sourcemap(){
// run webpack
return gulp.src('index.js').pipe(webpackStream(createWebpackConfig({
mode: 'development',
entry: npmEntry,
output: {
filename:'oidc-client.js',
libraryTarget:'umd',
// Workaround for https://github.com/webpack/webpack/issues/6642
globalObject: 'this'
},
plugins: [],
devtool:'inline-source-map'
}), webpack))
.pipe(gulp.dest('lib/'));
}
|
javascript
|
{
"resource": ""
}
|
q22990
|
build_lib_min
|
train
|
function build_lib_min(){
// run webpack
return gulp.src('index.js').pipe(webpackStream(createWebpackConfig({
mode: 'production',
entry: npmEntry,
output: {
filename:'oidc-client.min.js',
libraryTarget:'umd',
// Workaround for https://github.com/webpack/webpack/issues/6642
globalObject: 'this'
},
plugins: [],
devtool: false,
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
keep_fnames: true
}
})
]
}
}), webpack))
.pipe(gulp.dest('lib/'));
}
|
javascript
|
{
"resource": ""
}
|
q22991
|
build_dist_sourcemap
|
train
|
function build_dist_sourcemap(){
// run webpack
return gulp.src('index.js').pipe(webpackStream(createWebpackConfig({
mode: 'development',
entry: classicEntry,
output: {
filename:'oidc-client.js',
libraryTarget:'var',
library:'Oidc'
},
plugins: [],
devtool:'inline-source-map'
}), webpack))
.pipe(gulp.dest('dist/'));
}
|
javascript
|
{
"resource": ""
}
|
q22992
|
build_dist_min
|
train
|
function build_dist_min(){
// run webpack
return gulp.src('index.js').pipe(webpackStream(createWebpackConfig({
mode: 'production',
entry: classicEntry,
output: {
filename:'oidc-client.min.js',
libraryTarget:'var',
library:'Oidc'
},
plugins: [],
devtool: false,
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
keep_fnames: true
}
})
]
}
}), webpack))
.pipe(gulp.dest('dist/'));
}
|
javascript
|
{
"resource": ""
}
|
q22993
|
share
|
train
|
function share(elem, options) {
var data = mixin({}, defaults, options || {}, dataset(elem));
if (data.imageSelector) {
data.image = querySelectorAlls(data.imageSelector).map(function(item) {
return item.src;
}).join('||');
}
addClass(elem, 'share-component social-share');
createIcons(elem, data);
createWechat(elem, data);
elem.initialized = true;
}
|
javascript
|
{
"resource": ""
}
|
q22994
|
makeUrl
|
train
|
function makeUrl(name, data) {
if (! data['summary']){
data['summary'] = data['description'];
}
return templates[name].replace(/\{\{(\w)(\w*)\}\}/g, function (m, fix, key) {
var nameKey = name + fix + key.toLowerCase();
key = (fix + key).toLowerCase();
return encodeURIComponent((data[nameKey] === undefined ? data[key] : data[nameKey]) || '');
});
}
|
javascript
|
{
"resource": ""
}
|
q22995
|
querySelectorAlls
|
train
|
function querySelectorAlls(str) {
return (document.querySelectorAll || window.jQuery || window.Zepto || selector).call(document, str);
}
|
javascript
|
{
"resource": ""
}
|
q22996
|
selector
|
train
|
function selector(str) {
var elems = [];
each(str.split(/\s*,\s*/), function(s) {
var m = s.match(/([#.])(\w+)/);
if (m === null) {
throw Error('Supports only simple single #ID or .CLASS selector.');
}
if (m[1]) {
var elem = document.getElementById(m[2]);
if (elem) {
elems.push(elem);
}
}
elems = elems.concat(getElementsByClassName(str));
});
return elems;
}
|
javascript
|
{
"resource": ""
}
|
q22997
|
addClass
|
train
|
function addClass(elem, value) {
if (value && typeof value === "string") {
var classNames = (elem.className + ' ' + value).split(/\s+/);
var setClass = ' ';
each(classNames, function (className) {
if (setClass.indexOf(' ' + className + ' ') < 0) {
setClass += className + ' ';
}
});
elem.className = setClass.slice(1, -1);
}
}
|
javascript
|
{
"resource": ""
}
|
q22998
|
getElementsByClassName
|
train
|
function getElementsByClassName(elem, name, tag) {
if (elem.getElementsByClassName) {
return elem.getElementsByClassName(name);
}
var elements = [];
var elems = elem.getElementsByTagName(tag || '*');
name = ' ' + name + ' ';
each(elems, function (elem) {
if ((' ' + (elem.className || '') + ' ').indexOf(name) >= 0) {
elements.push(elem);
}
});
return elements;
}
|
javascript
|
{
"resource": ""
}
|
q22999
|
createElementByString
|
train
|
function createElementByString(str) {
var div = document.createElement('div');
div.innerHTML = str;
return div.childNodes;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.