_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q27700 | listenToEmberDebugPort | train | function listenToEmberDebugPort(emberDebugPort) {
// listen for messages from EmberDebug, and pass them on to the background-script
emberDebugPort.addEventListener('message', function(event) {
chrome.runtime.sendMessage(event.data);
});
// listen for messages from the EmberInspector, and pass the... | javascript | {
"resource": ""
} |
q27701 | onApplicationStart | train | function onApplicationStart(callback) {
if (typeof Ember === 'undefined') {
return;
}
const adapterInstance = requireModule('ember-debug/adapters/' + currentAdapter)['default'].create();
adapterInstance.onMessageReceived(function(message) {
if (message.type === 'app-picker-loaded') {
... | javascript | {
"resource": ""
} |
q27702 | getApplications | train | function getApplications() {
var namespaces = Ember.A(Ember.Namespace.NAMESPACES);
var apps = namespaces.filter(function(namespace) {
return namespace instanceof Ember.Application;
});
return apps.map(function(app) {
// Add applicationId and applicationName to the app
var application... | javascript | {
"resource": ""
} |
q27703 | sendVersionMiss | train | function sendVersionMiss() {
var adapter = requireModule('ember-debug/adapters/' + currentAdapter)['default'].create();
adapter.onMessageReceived(function(message) {
if (message.type === 'check-version') {
sendVersionMismatch();
}
});
sendVersionMismatch();
function sendVersionM... | javascript | {
"resource": ""
} |
q27704 | compareVersion | train | function compareVersion(version1, version2) {
version1 = cleanupVersion(version1).split('.');
version2 = cleanupVersion(version2).split('.');
for (let i = 0; i < 3; i++) {
let compared = compare(+version1[i], +version2[i]);
if (compared !== 0) {
return compared;
}
}
return 0;
} | javascript | {
"resource": ""
} |
q27705 | parse | train | function parse(any, opts) {
var schema;
if (typeof any == 'string') {
try {
schema = JSON.parse(any);
} catch (err) {
schema = any;
}
} else {
schema = any;
}
return types.Type.forSchema(schema, opts);
} | javascript | {
"resource": ""
} |
q27706 | bufferFrom | train | function bufferFrom(data, enc) {
if (typeof Buffer.from == 'function') {
return Buffer.from(data, enc);
} else {
return new Buffer(data, enc);
}
} | javascript | {
"resource": ""
} |
q27707 | getOption | train | function getOption(opts, key, def) {
var value = opts[key];
return value === undefined ? def : value;
} | javascript | {
"resource": ""
} |
q27708 | getHash | train | function getHash(str, algorithm) {
algorithm = algorithm || 'md5';
var hash = crypto.createHash(algorithm);
hash.end(str);
return hash.read();
} | javascript | {
"resource": ""
} |
q27709 | singleIndexOf | train | function singleIndexOf(arr, v) {
var pos = -1;
var i, l;
if (!arr) {
return -1;
}
for (i = 0, l = arr.length; i < l; i++) {
if (arr[i] === v) {
if (pos >= 0) {
return -2;
}
pos = i;
}
}
return pos;
} | javascript | {
"resource": ""
} |
q27710 | toMap | train | function toMap(arr, fn) {
var obj = {};
var i, elem;
for (i = 0; i < arr.length; i++) {
elem = arr[i];
obj[fn(elem)] = elem;
}
return obj;
} | javascript | {
"resource": ""
} |
q27711 | hasDuplicates | train | function hasDuplicates(arr, fn) {
var obj = {};
var i, l, elem;
for (i = 0, l = arr.length; i < l; i++) {
elem = arr[i];
if (fn) {
elem = fn(elem);
}
if (obj[elem]) {
return true;
}
obj[elem] = true;
}
return false;
} | javascript | {
"resource": ""
} |
q27712 | copyOwnProperties | train | function copyOwnProperties(src, dst, overwrite) {
var names = Object.getOwnPropertyNames(src);
var i, l, name;
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (!dst.hasOwnProperty(name) || overwrite) {
var descriptor = Object.getOwnPropertyDescriptor(src, name);
Object.definePr... | javascript | {
"resource": ""
} |
q27713 | addDeprecatedGetters | train | function addDeprecatedGetters(obj, props) {
var proto = obj.prototype;
var i, l, prop, getter;
for (i = 0, l = props.length; i < l; i++) {
prop = props[i];
getter = 'get' + capitalize(prop);
proto[getter] = util.deprecate(
createGetter(prop),
'use `.' + prop + '` instead of `.' + getter + ... | javascript | {
"resource": ""
} |
q27714 | Lcg | train | function Lcg(seed) {
var a = 1103515245;
var c = 12345;
var m = Math.pow(2, 31);
var state = Math.floor(seed || Math.random() * (m - 1));
this._max = m;
this._nextInt = function () { return state = (a * state + c) % m; };
} | javascript | {
"resource": ""
} |
q27715 | parse | train | function parse(any, opts) {
var schemaOrProtocol = specs.read(any);
return schemaOrProtocol.protocol ?
services.Service.forProtocol(schemaOrProtocol, opts) :
types.Type.forSchema(schemaOrProtocol, opts);
} | javascript | {
"resource": ""
} |
q27716 | createFileDecoder | train | function createFileDecoder(path, opts) {
return fs.createReadStream(path)
.pipe(new containers.streams.BlockDecoder(opts));
} | javascript | {
"resource": ""
} |
q27717 | createFileEncoder | train | function createFileEncoder(path, schema, opts) {
var encoder = new containers.streams.BlockEncoder(schema, opts);
encoder.pipe(fs.createWriteStream(path, {defaultEncoding: 'binary'}));
return encoder;
} | javascript | {
"resource": ""
} |
q27718 | FixedType | train | function FixedType(schema, opts) {
Type.call(this, schema, opts);
if (schema.size !== (schema.size | 0) || schema.size < 1) {
throw new Error(f('invalid %s size', this.branchName));
}
this.size = schema.size | 0;
this._branchConstructor = this._createBranchConstructor();
Object.freeze(this);
} | javascript | {
"resource": ""
} |
q27719 | MapType | train | function MapType(schema, opts) {
Type.call(this);
if (!schema.values) {
throw new Error(f('missing map values: %j', schema));
}
this.valuesType = Type.forSchema(schema.values, opts);
this._branchConstructor = this._createBranchConstructor();
Object.freeze(this);
} | javascript | {
"resource": ""
} |
q27720 | ArrayType | train | function ArrayType(schema, opts) {
Type.call(this);
if (!schema.items) {
throw new Error(f('missing array items: %j', schema));
}
this.itemsType = Type.forSchema(schema.items, opts);
this._branchConstructor = this._createBranchConstructor();
Object.freeze(this);
} | javascript | {
"resource": ""
} |
q27721 | Field | train | function Field(schema, opts) {
var name = schema.name;
if (typeof name != 'string' || !isValidName(name)) {
throw new Error(f('invalid field name: %s', name));
}
this.name = name;
this.type = Type.forSchema(schema.type, opts);
this.aliases = schema.aliases || [];
this.doc = schema.doc !== undefined ?... | javascript | {
"resource": ""
} |
q27722 | readValue | train | function readValue(type, tap, resolver, lazy) {
if (resolver) {
if (resolver._readerType !== type) {
throw new Error('invalid resolver');
}
return resolver._read(tap, lazy);
} else {
return type._read(tap);
}
} | javascript | {
"resource": ""
} |
q27723 | qualify | train | function qualify(name, namespace) {
if (~name.indexOf('.')) {
name = name.replace(/^\./, ''); // Allow absolute referencing.
} else if (namespace) {
name = namespace + '.' + name;
}
name.split('.').forEach(function (part) {
if (!isValidName(part)) {
throw new Error(f('invalid name: %j', name))... | javascript | {
"resource": ""
} |
q27724 | getClassName | train | function getClassName(typeName) {
if (typeName === 'error') {
typeName = 'record';
} else {
var match = /^([^:]+):(.*)$/.exec(typeName);
if (match) {
if (match[1] === 'union') {
typeName = match[2] + 'Union';
} else {
// Logical type.
typeName = match[1];
}
... | javascript | {
"resource": ""
} |
q27725 | readArraySize | train | function readArraySize(tap) {
var n = tap.readLong();
if (n < 0) {
n = -n;
tap.skipLong(); // Skip size.
}
return n;
} | javascript | {
"resource": ""
} |
q27726 | isAmbiguous | train | function isAmbiguous(types) {
var buckets = {};
var i, l, bucket, type;
for (i = 0, l = types.length; i < l; i++) {
type = types[i];
if (!Type.isType(type, 'logical')) {
bucket = getTypeBucket(type);
if (buckets[bucket]) {
return true;
}
buckets[bucket] = true;
}
}
... | javascript | {
"resource": ""
} |
q27727 | combineNumbers | train | function combineNumbers(types) {
var typeNames = ['int', 'long', 'float', 'double'];
var superIndex = -1;
var superType = null;
var i, l, type, index;
for (i = 0, l = types.length; i < l; i++) {
type = types[i];
index = typeNames.indexOf(type.typeName);
if (index > superIndex) {
superIndex =... | javascript | {
"resource": ""
} |
q27728 | generateStats | train | function generateStats(schema, opts) {
opts = opts || {};
var type = avro.parse(schema, {wrapUnions: opts.wrapUnions});
return [DecodeSuite, EncodeSuite].map(function (Suite) {
var stats = [];
var suite = new Suite(type, opts)
.on('start', function () { console.error(Suite.key_ + ' ' + type); })
... | javascript | {
"resource": ""
} |
q27729 | Suite | train | function Suite(type, opts) {
Benchmark.Suite.call(this);
opts = opts || {};
this._type = type;
this._compatibleType = avro.parse(type.getSchema(), {
typeHook: typeHook,
wrapUnions: opts.wrapUnions
});
this._value = opts.value ? type.fromString(opts.value) : type.random();
Object.keys(opts).forEa... | javascript | {
"resource": ""
} |
q27730 | read | train | function read(str) {
var schema;
if (typeof str == 'string' && ~str.indexOf(path.sep) && files.existsSync(str)) {
// Try interpreting `str` as path to a file contain a JSON schema or an IDL
// protocol. Note that we add the second check to skip primitive references
// (e.g. `"int"`, the most common use-... | javascript | {
"resource": ""
} |
q27731 | extractJavadoc | train | function extractJavadoc(str) {
var lines = str
.replace(/^[ \t]+|[ \t]+$/g, '') // Trim whitespace.
.split('\n').map(function (line, i) {
return i ? line.replace(/^\s*\*\s?/, '') : line;
});
while (!lines[0]) {
lines.shift();
}
while (!lines[lines.length - 1]) {
lines.pop();
}
retu... | javascript | {
"resource": ""
} |
q27732 | BlobReader | train | function BlobReader(blob, opts) {
stream.Readable.call(this);
opts = opts || {};
this._batchSize = opts.batchSize || 65536;
this._blob = blob;
this._pos = 0;
} | javascript | {
"resource": ""
} |
q27733 | createBlobDecoder | train | function createBlobDecoder(blob, opts) {
return new BlobReader(blob).pipe(new containers.streams.BlockDecoder(opts));
} | javascript | {
"resource": ""
} |
q27734 | createBlobEncoder | train | function createBlobEncoder(schema, opts) {
var encoder = new containers.streams.BlockEncoder(schema, opts);
var builder = new BlobWriter();
encoder.pipe(builder);
return new stream.Duplex({
objectMode: true,
read: function () {
// Not the fastest implementation, but it will only be called at most
... | javascript | {
"resource": ""
} |
q27735 | BlockData | train | function BlockData(index, buf, cb, count) {
this.index = index;
this.buf = buf;
this.cb = cb;
this.count = count | 0;
} | javascript | {
"resource": ""
} |
q27736 | tryReadBlock | train | function tryReadBlock(tap) {
var pos = tap.pos;
var block = BLOCK_TYPE._read(tap);
if (!tap.isValid()) {
tap.pos = pos;
return null;
}
return block;
} | javascript | {
"resource": ""
} |
q27737 | copyBuffer | train | function copyBuffer(buf, pos, len) {
var copy = utils.newBuffer(len);
buf.copy(copy, 0, pos, pos + len);
return copy;
} | javascript | {
"resource": ""
} |
q27738 | Message | train | function Message(name, reqType, errType, resType, oneWay, doc) {
this.name = name;
if (!Type.isType(reqType, 'record')) {
throw new Error('invalid request type');
}
this.requestType = reqType;
if (
!Type.isType(errType, 'union') ||
!Type.isType(errType.getTypes()[0], 'string')
) {
throw new ... | javascript | {
"resource": ""
} |
q27739 | Service | train | function Service(name, messages, types, ptcl, server) {
if (typeof name != 'string') {
// Let's be helpful in case this class is instantiated directly.
return Service.forProtocol(name, messages);
}
this.name = name;
this._messagesByName = messages || {};
this.messages = Object.freeze(utils.objectValu... | javascript | {
"resource": ""
} |
q27740 | discoverProtocol | train | function discoverProtocol(transport, opts, cb) {
if (cb === undefined && typeof opts == 'function') {
cb = opts;
opts = undefined;
}
var svc = new Service({protocol: 'Empty'}, OPTS);
var ptclStr;
svc.createClient({timeout: opts && opts.timeout})
.createChannel(transport, {
scope: opts && op... | javascript | {
"resource": ""
} |
q27741 | Client | train | function Client(svc, opts) {
opts = opts || {};
events.EventEmitter.call(this);
// We have to suffix all client properties to be safe, since the message
// names aren't prefixed with clients (unlike servers).
this._svc$ = svc;
this._channels$ = []; // Active channels.
this._fns$ = []; // Middleware funct... | javascript | {
"resource": ""
} |
q27742 | Server | train | function Server(svc, opts) {
opts = opts || {};
events.EventEmitter.call(this);
this.service = svc;
this._handlers = {};
this._fns = []; // Middleware functions.
this._channels = {}; // Active channels.
this._nextChannelId = 1;
this._cache = opts.cache || {}; // Deprecated.
this._defaultHandler = op... | javascript | {
"resource": ""
} |
q27743 | ClientChannel | train | function ClientChannel(client, opts) {
opts = opts || {};
events.EventEmitter.call(this);
this.client = client;
this.timeout = utils.getOption(opts, 'timeout', client._timeout$);
this._endWritable = !!utils.getOption(opts, 'endWritable', true);
this._prefix = normalizedPrefix(opts.scope);
var cache = cl... | javascript | {
"resource": ""
} |
q27744 | StatelessClientChannel | train | function StatelessClientChannel(client, writableFactory, opts) {
ClientChannel.call(this, client, opts);
this._writableFactory = writableFactory;
if (!opts || !opts.noPing) {
// Ping the server to check whether the remote protocol is compatible.
// If not, this will throw an error on the channel.
deb... | javascript | {
"resource": ""
} |
q27745 | onMessage | train | function onMessage(obj) {
var id = obj.id;
if (!self._matchesPrefix(id)) {
debug('discarding unscoped message %s', id);
return;
}
var cb = self._registry.get(id);
if (cb) {
process.nextTick(function () {
debug('received message %s', id);
// Ensure that the initial c... | javascript | {
"resource": ""
} |
q27746 | StatelessServerChannel | train | function StatelessServerChannel(server, readableFactory, opts) {
ServerChannel.call(this, server, opts);
this._writable = undefined;
var self = this;
var readable;
process.nextTick(function () {
// Delay listening to allow handlers to be attached even if the factory is
// purely synchronous.
rea... | javascript | {
"resource": ""
} |
q27747 | WrappedRequest | train | function WrappedRequest(msg, hdrs, req) {
this._msg = msg;
this.headers = hdrs || {};
this.request = req || {};
} | javascript | {
"resource": ""
} |
q27748 | WrappedResponse | train | function WrappedResponse(msg, hdr, err, res) {
this._msg = msg;
this.headers = hdr;
this.error = err;
this.response = res;
} | javascript | {
"resource": ""
} |
q27749 | CallContext | train | function CallContext(msg, channel) {
this.channel = channel;
this.locals = {};
this.message = msg;
Object.freeze(this);
} | javascript | {
"resource": ""
} |
q27750 | Registry | train | function Registry(ctx, prefixLength) {
this._ctx = ctx; // Context for all callbacks.
this._mask = ~0 >>> (prefixLength | 0); // 16 bits by default.
this._id = 0; // Unique integer ID for each call.
this._n = 0; // Number of pending calls.
this._cbs = {};
} | javascript | {
"resource": ""
} |
q27751 | Adapter | train | function Adapter(clientSvc, serverSvc, hash, isRemote) {
this._clientSvc = clientSvc;
this._serverSvc = serverSvc;
this._hash = hash; // Convenience to access it when creating handshakes.
this._isRemote = !!isRemote;
this._readers = createReaders(clientSvc, serverSvc);
} | javascript | {
"resource": ""
} |
q27752 | FrameDecoder | train | function FrameDecoder() {
stream.Transform.call(this, {readableObjectMode: true});
this._id = undefined;
this._buf = utils.newBuffer(0);
this._bufs = [];
this.on('finish', function () { this.push(null); });
} | javascript | {
"resource": ""
} |
q27753 | readHead | train | function readHead(type, buf) {
var tap = new Tap(buf);
var head = type._read(tap);
if (!tap.isValid()) {
throw new Error(f('truncated %j', type.schema()));
}
return {head: head, tail: tap.buf.slice(tap.pos)};
} | javascript | {
"resource": ""
} |
q27754 | createReader | train | function createReader(rtype, wtype) {
return rtype.equals(wtype) ? rtype : rtype.createResolver(wtype);
} | javascript | {
"resource": ""
} |
q27755 | createReaders | train | function createReaders(clientSvc, serverSvc) {
var obj = {};
clientSvc.messages.forEach(function (c) {
var n = c.name;
var s = serverSvc.message(n);
try {
if (!s) {
throw new Error(f('missing server message: %s', n));
}
if (s.oneWay !== c.oneWay) {
throw new Error(f('in... | javascript | {
"resource": ""
} |
q27756 | insertRemoteProtocols | train | function insertRemoteProtocols(cache, ptcls, svc, isClient) {
Object.keys(ptcls).forEach(function (hash) {
var ptcl = ptcls[hash];
var clientSvc, serverSvc;
if (isClient) {
clientSvc = svc;
serverSvc = Service.forProtocol(ptcl);
} else {
clientSvc = Service.forProtocol(ptcl);
s... | javascript | {
"resource": ""
} |
q27757 | getRemoteProtocols | train | function getRemoteProtocols(cache, isClient) {
var ptcls = {};
Object.keys(cache).forEach(function (hs) {
var adapter = cache[hs];
if (adapter._isRemote) {
var svc = isClient ? adapter._serverSvc : adapter._clientSvc;
ptcls[hs] = svc.protocol;
}
});
return ptcls;
} | javascript | {
"resource": ""
} |
q27758 | forwardErrors | train | function forwardErrors(src, dst) {
return src.on('error', function (err) {
dst.emit('error', err, src);
});
} | javascript | {
"resource": ""
} |
q27759 | toError | train | function toError(msg, cause) {
var err = new Error(msg);
err.cause = cause;
return err;
} | javascript | {
"resource": ""
} |
q27760 | toRpcError | train | function toRpcError(rpcCode, cause) {
var err = toError(rpcCode.toLowerCase().replace(/_/g, ' '), cause);
err.rpcCode = (cause && cause.rpcCode) ? cause.rpcCode : rpcCode;
return err;
} | javascript | {
"resource": ""
} |
q27761 | serializationError | train | function serializationError(msg, obj, fields) {
var details = [];
var i, l, field;
for (i = 0, l = fields.length; i < l; i++) {
field = fields[i];
field.type.isValid(obj[field.name], {errorHook: errorHook});
}
var detailsStr = details
.map(function (obj) {
return f('%s = %j but expected %s',... | javascript | {
"resource": ""
} |
q27762 | getExistingMessage | train | function getExistingMessage(svc, name) {
var msg = svc.message(name);
if (!msg) {
throw new Error(f('unknown message: %s', name));
}
return msg;
} | javascript | {
"resource": ""
} |
q27763 | chainMiddleware | train | function chainMiddleware(params) {
var args = [params.wreq, params.wres];
var cbs = [];
var cause; // Backpropagated error.
forward(0);
function forward(pos) {
var isDone = false;
if (pos < params.fns.length) {
params.fns[pos].apply(params.ctx, args.concat(function (err, cb) {
if (isDon... | javascript | {
"resource": ""
} |
q27764 | getAvailableLocales | train | function getAvailableLocales() {
if (Cldr._raw && Cldr._raw.main) {
return Object.keys(Cldr._raw.main);
}
return [];
} | javascript | {
"resource": ""
} |
q27765 | findFallbackLocale | train | function findFallbackLocale(locale) {
const locales = getAvailableLocales();
for (let i = locale.length - 1; i > 1; i -= 1) {
const key = locale.substring(0, i);
if (locales.includes(key)) {
return key;
}
}
return null;
} | javascript | {
"resource": ""
} |
q27766 | localeIsLoaded | train | function localeIsLoaded(locale) {
return !!(Cldr._raw && Cldr._raw.main && Cldr._raw.main[getLocaleKey(locale)]);
} | javascript | {
"resource": ""
} |
q27767 | getCurrencySymbol | train | function getCurrencySymbol(locale, currencyCode, altNarrow) {
// Check whether the locale has been loaded
if (!localeIsLoaded(locale)) {
return null;
}
const { currencies } = Cldr._raw.main[locale].numbers;
// Check whether the given currency code exists within the CLDR file for the given locale
if (!... | javascript | {
"resource": ""
} |
q27768 | shouldUpdateVideo | train | function shouldUpdateVideo(prevProps, props) {
// A changing video should always trigger an update
if (prevProps.videoId !== props.videoId) {
return true;
}
// Otherwise, a change in the start/end time playerVars also requires a player
// update.
const prevVars = prevProps.opts.playerVars || {};
cons... | javascript | {
"resource": ""
} |
q27769 | shouldResetPlayer | train | function shouldResetPlayer(prevProps, props) {
return !isEqual(
filterResetOptions(prevProps.opts),
filterResetOptions(props.opts),
);
} | javascript | {
"resource": ""
} |
q27770 | shouldUpdatePlayer | train | function shouldUpdatePlayer(prevProps, props) {
return (
prevProps.id !== props.id || prevProps.className !== props.className
);
} | javascript | {
"resource": ""
} |
q27771 | loadDatabase | train | function loadDatabase(config = {}) {
if (typeof config.ignore === 'string' || Array.isArray(config.ignore)) {
app.deprecate(`[egg-sequelize] if you want to exclude ${config.ignore} when load models, please set to config.sequelize.exclude instead of config.sequelize.ignore`);
config.exclude = config.igno... | javascript | {
"resource": ""
} |
q27772 | authenticate | train | async function authenticate(database) {
database[AUTH_RETRIES] = database[AUTH_RETRIES] || 0;
try {
await database.authenticate();
} catch (e) {
if (e.name !== 'SequelizeConnectionRefusedError') throw e;
if (app.model[AUTH_RETRIES] >= 3) throw e;
// sleep 2s to retry, max 3 times
... | javascript | {
"resource": ""
} |
q27773 | copyTimeFromDateToDate | train | function copyTimeFromDateToDate(date1, date2) {
date2.setHours(date1.getHours());
date2.setMinutes(date1.getMinutes());
date2.setSeconds(date1.getSeconds());
date2.setMilliseconds(date1.getMilliseconds());
} | javascript | {
"resource": ""
} |
q27774 | updateDays | train | function updateDays(state, forceCreation) {
const { dayCount, dayRole, locale, showCompleteWeeks, startDate } = state;
const workingStartDate = showCompleteWeeks ?
calendar.firstDateOfWeek(startDate, locale) :
calendar.midnightOnDate(startDate);
let workingDayCount;
if (showCompleteWeeks) {
const en... | javascript | {
"resource": ""
} |
q27775 | prepareTemplate | train | function prepareTemplate(element) {
let template = element[symbols.template];
if (!template) {
/* eslint-disable no-console */
console.warn(`ShadowTemplateMixin expects ${element.constructor.name} to define a property called [symbols.template].\nSee https://elix.org/documentation/ShadowTemplateMixin.`);
... | javascript | {
"resource": ""
} |
q27776 | measurePopup | train | function measurePopup(element) {
const windowHeight = window.innerHeight;
const windowWidth = window.innerWidth;
const popupRect = element.$.popup.getBoundingClientRect();
const popupHeight = popupRect.height;
const popupWidth = popupRect.width;
const sourceRect = element.getBoundingClientRect();
con... | javascript | {
"resource": ""
} |
q27777 | getLocaleOptions | train | function getLocaleOptions() {
if (!localeOptions) {
localeOptions = Object.keys(locales).map(locale => {
const option = document.createElement('option');
option.value = locale;
option.disabled = !localeSupported(locale);
option.textContent = locales[locale];
return option;
});
... | javascript | {
"resource": ""
} |
q27778 | localeSupported | train | function localeSupported(locale) {
const language = locale.split('-')[0];
if (language === 'en') {
// Assume all flavors of English are supported.
return true;
}
// Try formatting a Tuesday date, and if we get the English result "Tue",
// the browser probably doesn't support the locale, and used the d... | javascript | {
"resource": ""
} |
q27779 | disableDocumentScrolling | train | function disableDocumentScrolling(element) {
if (!document.documentElement) {
return;
}
const documentWidth = document.documentElement.clientWidth;
const scrollBarWidth = window.innerWidth - documentWidth;
element[previousBodyOverflowKey] = document.body.style.overflow;
element[previousDocumentMarginRig... | javascript | {
"resource": ""
} |
q27780 | openedChanged | train | function openedChanged(element) {
if (element.state.autoFocus) {
if (element.state.opened) {
// Opened
if (!element[restoreFocusToElementKey] && document.activeElement !== document.body) {
// Remember which element had the focus before we were opened.
element[restoreFocusToElementKey] ... | javascript | {
"resource": ""
} |
q27781 | formatWeekDataAsModule | train | function formatWeekDataAsModule(weekData) {
const date = new Date();
const { firstDay, weekendEnd, weekendStart } = weekData;
const transformed = {
firstDay: transformWeekDays(firstDay),
weekendEnd: transformWeekDays(weekendEnd),
weekendStart: transformWeekDays(weekendStart)
};
const formatted = J... | javascript | {
"resource": ""
} |
q27782 | getTextFromContent | train | function getTextFromContent(contentNodes) {
if (contentNodes === null) {
return '';
}
const texts = [...contentNodes].map(node => node.textContent);
const text = texts.join('').trim();
return unescapeHtml(text);
} | javascript | {
"resource": ""
} |
q27783 | isEmpty | train | function isEmpty(o) {
for (var key in o) {
if (o.hasOwnProperty(key)) {
return false;
}
}
return Object.getOwnPropertySymbols(o).length === 0;
} | javascript | {
"resource": ""
} |
q27784 | PageNumbersMixin | train | function PageNumbersMixin(Base) {
class PageNumbers extends Base {
/**
* Destructively wrap a node with elements to show page numbers.
*
* @param {Node} original - the element that should be wrapped by page numbers
*/
[wrap](original) {
const pageNumbersTemplate = template.html`
... | javascript | {
"resource": ""
} |
q27785 | attributeToPropertyName | train | function attributeToPropertyName(attributeName) {
let propertyName = attributeToPropertyNames[attributeName];
if (!propertyName) {
// Convert and memoize.
const hyphenRegEx = /-([a-z])/g;
propertyName = attributeName.replace(hyphenRegEx,
match => match[1].toUpperCase());
attributeToPropertyN... | javascript | {
"resource": ""
} |
q27786 | propertyNameToAttribute | train | function propertyNameToAttribute(propertyName) {
let attribute = propertyNamesToAttributes[propertyName];
if (!attribute) {
// Convert and memoize.
const uppercaseRegEx = /([A-Z])/g;
attribute = propertyName.replace(uppercaseRegEx, '-$1').toLowerCase();
}
return attribute;
} | javascript | {
"resource": ""
} |
q27787 | assignedNodesChanged | train | function assignedNodesChanged(component) {
const slot = component[symbols.contentSlot];
const content = slot ?
slot.assignedNodes({ flatten: true }) :
null;
// Make immutable.
Object.freeze(content);
component.setState({ content });
} | javascript | {
"resource": ""
} |
q27788 | FocusCaptureMixin | train | function FocusCaptureMixin(base) {
class FocusCapture extends base {
componentDidMount() {
if (super.componentDidMount) { super.componentDidMount(); }
this.$.focusCatcher.addEventListener('focus', () => {
if (!this[wrappingFocusKey]) {
// Wrap focus back to the first focusable elem... | javascript | {
"resource": ""
} |
q27789 | handleScrollPull | train | async function handleScrollPull(element, scrollTarget) {
const scrollTop = scrollTarget === window ?
document.body.scrollTop :
scrollTarget.scrollTop;
if (scrollTop < 0) {
// Negative scroll top means we're probably in WebKit.
// Start a scroll pull operation.
let scrollPullDistance = -scrollTop... | javascript | {
"resource": ""
} |
q27790 | updateTimer | train | function updateTimer(element) {
// If the element is playing and we haven't started a timer yet, do so now.
// Also, if the element's selectedIndex changed for any reason, restart the
// timer. This ensures that the timer restarts no matter why the selection
// changes: it could have been us moving to the next ... | javascript | {
"resource": ""
} |
q27791 | resetWheelTracking | train | function resetWheelTracking(element) {
element[wheelDistanceSymbol] = 0;
element[lastDeltaXSymbol] = 0;
element[absorbDecelerationSymbol] = false;
element[postNavigateDelayCompleteSymbol] = false;
if (element[lastWheelTimeoutSymbol]) {
clearTimeout(element[lastWheelTimeoutSymbol]);
element[lastWheelTi... | javascript | {
"resource": ""
} |
q27792 | handlePlainCharacter | train | function handlePlainCharacter(element, char) {
const prefix = element[typedPrefixKey] || '';
element[typedPrefixKey] = prefix + char;
element.selectItemWithTextPrefix(element[typedPrefixKey]);
setPrefixTimeout(element);
} | javascript | {
"resource": ""
} |
q27793 | resetPrefixTimeout | train | function resetPrefixTimeout(element) {
if (element[prefixTimeoutKey]) {
clearTimeout(element[prefixTimeoutKey]);
element[prefixTimeoutKey] = false;
}
} | javascript | {
"resource": ""
} |
q27794 | setPrefixTimeout | train | function setPrefixTimeout(element) {
resetPrefixTimeout(element);
element[prefixTimeoutKey] = setTimeout(() => {
resetTypedPrefix(element);
}, TYPING_TIMEOUT_DURATION);
} | javascript | {
"resource": ""
} |
q27795 | jd0 | train | function jd0(year, month, day) {
let y = year;
let m = month;
if (m < 3) {
m += 12;
y -= 1
};
const a = Math.floor(y/100);
const b = 2-a+Math.floor(a/4);
const j = Math.floor(365.25*(y+4716))+Math.floor(30.6001*(m+1))+day+b-1524.5;
return j;
} | javascript | {
"resource": ""
} |
q27796 | createDefaultProxies | train | function createDefaultProxies(items, proxyRole) {
const proxies = items ?
items.map(() => template.createElement(proxyRole)) :
[];
// Make the array immutable to help update performance.
Object.freeze(proxies);
return proxies;
} | javascript | {
"resource": ""
} |
q27797 | findChildContainingNode | train | function findChildContainingNode(root, node) {
const parentNode = node.parentNode;
return parentNode === root ?
node :
findChildContainingNode(root, parentNode);
} | javascript | {
"resource": ""
} |
q27798 | setListAndStageOrder | train | function setListAndStageOrder(element) {
const proxyListPosition = element.state.proxyListPosition;
const rightToLeft = element[symbols.rightToLeft];
const listInInitialPosition =
proxyListPosition === 'top' ||
proxyListPosition === 'start' ||
proxyListPosition === 'left' && !rightToLeft ||
... | javascript | {
"resource": ""
} |
q27799 | generateAggregate | train | function generateAggregate (aggregateOp, defaultColumnName = undefined) {
let funcName = `get${_.upperFirst(aggregateOp)}`
/**
* Do not re-add the method if exists
*/
if (KnexQueryBuilder.prototype[funcName]) {
return
}
KnexQueryBuilder.prototype[funcName] = async function (columnName = defaultCol... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.